迭代二维python列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16548668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over a 2 dimensional python list
提问by bhaskarc
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
这个问题与纯 python 列表有关,而标记为相同的问题与 numpy 数组有关。它们明显不同
采纳答案by Alexey Kachayev
Use zipand itertools.chain. Something like:
使用zip和itertools.chain。就像是:
>>> from itertools import chain
>>> l = chain.from_iterable(zip(*l))
<itertools.chain object at 0x104612610>
>>> list(l)
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']
回答by Adrian Ratnapala
zipwill transpose the list, after that you can concatenate the outputs.
zip将转置列表,之后您可以连接输出。
In [3]: zip(*[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ])
Out[3]: [('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1')]
回答by dansalmo
>>> [el[0] if i < len(mylist) else el[1] for i,el in enumerate(mylist + mylist)]
['0,0', '1,0', '2,0', '0,1', '1,1', '2,1']
回答by Joran Beasley
>>> mylist = [["%s,%s"%(i,j) for j in range(columns)] for i in range(rows)]
>>> mylist
[['0,0', '0,1', '0,2'], ['1,0', '1,1', '1,2'], ['2,0', '2,1', '2,2']]
>>> zip(*mylist)
[('0,0', '1,0', '2,0'), ('0,1', '1,1', '2,1'), ('0,2', '1,2', '2,2')]
>>> sum(zip(*mylist),())
('0,0', '1,0', '2,0', '0,1', '1,1', '2,1', '0,2', '1,2', '2,2')
回答by mrKelley
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
>>>
回答by Iliyan Bobev
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
>>>
回答by Tanky Woo
参考:zip 内置函数
zip()in conjunction with the *operator can be used to unzipa list
zip()与*运算符结合使用可用于unzip列表
unzip_lst = zip(*mylist)
for i in unzip_lst:
for j in i:
print j

