请注意,这是一个简化的示例是否可以执行类似的操作
l=[[1,2,3],["a","b","c"],["x","y","z"]
然后有一个 for 循环,迭代每个列表中的所有第一个项目,然后是所有第二个项目,然后是所有第三个项目。
最佳答案
您可以使用zip(...)
函数。
>>> for elem in zip(*l):
for a in elem:
print(a)
1
a
x
2
b
y
3
c
z
另外,您可以使用 zip_longest(...)
(izip_longest
for Py2x)来处理长度不均匀的列表。
>>> from itertools import zip_longest
>>> l=[[1,2,3],["a","b","c"],["x","y"]]
>>> for elem in zip_longest(*l, fillvalue='Empty'):
print(elem)
(1, 'a', 'x')
(2, 'b', 'y')
(3, 'c', 'Empty')
关于python - 高级 Python 3 循环迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18087498/