有没有一种聪明的方法可以在 Python 中迭代两个列表(不使用列表理解)?
我的意思是,像这样:
# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
foo(a, b)
代替:
for a in list1:
for b in list2:
foo(a, b)
最佳答案
itertools.product()
正是这样做的:
for a, b in itertools.product(list1, list2):
foo(a, b)
它可以处理任意数量的迭代器,从这个意义上说,它比嵌套的 for
循环更通用。
关于Python多列表迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10418575/