0

I Have list of list, I want to loop through the list and for every iteration i want to access the ith subelements of the list.

eg:

a = [[1, 3, 4], [2, 4, 4], [3, 7, 5]]

i want to do something like this

   for i in range(len(a)):
        x=a[i]

for 1st iteration I want to access the 0th element from all the sub list (i.e) 1,2,3

for 2nd iteration I want to access the 1st element from all the sub list (i.e) 3,4,7

I tried several approaches but failed, is there any trick to do that

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
arun
  • 123
  • 1
  • 12
  • What is your expected output? 123347? – Vincent Beltman Dec 05 '14 at 08:47
  • the expected output is I want to loop through the list and for every iteration I want to access the i th element of the sublist and i will do some writing to a html file with the obtained data from each iteration – arun Dec 05 '14 at 08:53

4 Answers4

5

You can use zip

s =  [[1, 3, 4], [2, 4, 4], [3, 7, 5]]
print zip(*s)
#[(1, 2, 3), (3, 4, 7), (4, 4, 5)]
Mitul Shah
  • 1,556
  • 1
  • 12
  • 34
0
def get_column(n, table):
    result = []
    for line in table:
        result.append(line[n])
    return result

test = [[1,2,3],[4,5,6],[7,8,9]]

for i in range(len(test[0])):
    print(get_column(i, test))

Execution :

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Arthur Vaïsse
  • 1,551
  • 1
  • 13
  • 26
0

As mentioned in above answer you can use an elegant way with zip but if you want to access to the columns in every iteration and dont want to get all of them in one time itertools.izip is what you are looking for , itertools.izip return a generator that you can get the result in every iteration :

>>> from itertools import izip
>>> for i in izip(*a):
...  print i
... 
(1, 2, 3)
(3, 4, 7)
(4, 4, 5)

Also you can use pop in a for loop (less performance than izip):

>>> a = [[1, 3, 4], [2, 4, 4], [3, 7, 5]]
>>> test=[]
>>> for i in range(len(a[0])):
...   for j in a:
...    test.append(j.pop(0))
...   print test
...   test=[]
... 
[1, 2, 3]
[3, 4, 7]
[4, 4, 5]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Alternative for the zip method,

>>> a = [[1, 3, 4], [2, 4, 4], [3, 7, 5]]
>>> new_list = []
>>> for k,v in enumerate(a):
...     new_list.append([])
...     for item in a:
...             new_list[-1].append(item[k])
... 
>>> new_list
[[1, 2, 3], [3, 4, 7], [4, 4, 5]]
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42