本文介绍了迭代二维python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个二维数组,如:
rows =3列= 2mylist = [[0 for x in range(columns)] for x in range(rows)]对于范围(行)中的 i:对于范围(列)中的 j:mylist[i][j] = '%s,%s'%(i,j)打印我的列表
打印这个列表给出一个输出:
[ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
其中每个列表项都是一个格式为'row,column'的字符串
现在给出这个列表,我想按顺序遍历它:
'0,0''1,0''2,0''0,1''1,1''2,1'
即迭代第一列然后第二列等等.我如何用循环来做到这一点?
这个问题属于纯 python 列表,而标记为相同的问题属于 numpy 数组.它们明显不同
解决方案
使用 zip
和 itertools.chain
.类似的东西:
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
解决方案
Use zip
and itertools.chain
. Something like:
>>> 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']
这篇关于迭代二维python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!