loops - Iterating over a 2 dimensional python list -
this question has answer here:
i have created 2 dimension array like:
rows =3 columns= 2 mylist = [[0 x in range(columns)] x in range(rows)] in range(rows): j in range(columns): mylist[i][j] = '%s,%s'%(i,j) print mylist
printing list gives output:
[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
where each list item string of format 'row,column'
now given list, want iterate through in order:
'0,0' '1,0' '2,0' '0,1' '1,1' '2,1'
that iterate through 1st column 2nd column , on. how do loop ?
this question pertains pure python list while question marked same pertains numpy arrays. different
use zip
, itertools.chain
. like:
>>> itertools import chain >>> l = chain.from_iterable(zip(*l)) <itertools.chain object @ 0x104612610> >>> list(l) ['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']
Comments
Post a Comment