Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a 2 dimensional python list [duplicate]

I have created a 2 dimension array like:

rows =3
columns= 2
mylist = [[0 for x in range(columns)] for x in range(rows)]
for i in range(rows):
    for j in range(columns):
        mylist[i][j] = '%s,%s'%(i,j)
print mylist

Printing this list gives an output:

[  ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1']   ]

where each list item is a string of the format 'row,column'

Now given this list, i want to iterate through it in the order:

'0,0'
'1,0'
'2,0'
'0,1'
'1,1'
'2,1'

that is iterate through 1st column then 2nd column and so on. How do i do it with a loop ?

This Question pertains to pure python list while the question which is marked as same pertains to numpy arrays. They are clearly different

like image 934
bhaskarc Avatar asked May 14 '13 16:05

bhaskarc


2 Answers

same way you did the fill in, but reverse the indexes:

>>> for j in range(columns):
...     for i in range(rows):
...        print mylist[i][j],
... 
0,0 1,0 2,0 0,1 1,1 2,1
>>> 
like image 100
Iliyan Bobev Avatar answered Oct 02 '22 16:10

Iliyan Bobev


This is the correct way.

>>> x = [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
>>> for i in range(len(x)):
        for j in range(len(x[i])):
                print(x[i][j])


0,0
0,1
1,0
1,1
2,0
2,1
>>> 
like image 45
mrKelley Avatar answered Oct 02 '22 15:10

mrKelley