如何以最pythonic的方式实现迭代多个列表?
假设我有 2 个列表:
l1 = [1, 2, 3]
l2 = [4, 5, 6]
如何在不改变 l1 和 l2 的情况下实现对 l1 和 l2 中整个元素集的迭代?
我可以简单地连接两个列表,然后遍历结果:
l3 = l1[:]
l3.extend(l2)
for e in l3:
# ... whatever with e
但在我看来,该解决方案并不像 pythonic 那样高效,因此我正在寻找更好的方法。
最佳答案
您可以使用 itertools.chain()
:
import itertools
for e in itertools.chain(l1, l2):
print e
与 l1 + l2
不同,这不需要为迭代创建临时列表。它也适用于任意可迭代对象和不同类型的序列。例如:
>>> l1 = (1, 2, 3)
>>> l2 = [4, 5, 6]
>>> l1 + l2 # can't loop over l1 + l2...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>> import itertools
>>> for e in itertools.chain(l1, l2):
... print e
...
1
2
3
4
5
6
关于python - 迭代多个 python 列表上的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18112393/