因此,我有以下清单:
test = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我想循环一下内部列表中的i
th元素。我可以通过使用zip
来做到这一点
for x, y, z in zip(test[0], test[1], test[2]):
print(x, y, z)
返回:
1 4 7
2 5 8
3 6 9
有没有一种更干净更毕达通的方法来做这件事?有点像zip(test, axis=0)
发布于 2017-04-25 14:22:20
您可以使用解压缩将输入的子列表作为变量参数传递给zip
:
for xyz in zip(*test):
print(*xyz)
(您也可以对x,y,z同弦进行同样的操作,以将params传递给print
)
发布于 2017-04-25 14:20:46
如果使用numpy.array
,只需使用数组的transpose
并对行进行迭代。
>>> import numpy as np
>>> test = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> t = np.array(test)
>>> t
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
然后迭代
for row in t.T:
print(row)
[1 4 7]
[2 5 8]
[3 6 9]
根据您的意图,numpy
可能比一般的列表理解效率更高。
https://stackoverflow.com/questions/43613260
复制相似问题