Python多列表迭代

use*_*064 7 python iteration list

有没有一种聪明的方法来迭代Python中的两个列表(不使用列表推导)?

我的意思是,像这样:

# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
   foo(a, b)
Run Code Online (Sandbox Code Playgroud)

代替:

for a in list1:
    for b in list2:
        foo(a, b)
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 13

itertools.product() 这样做:

for a, b in itertools.product(list1, list2):
  foo(a, b)
Run Code Online (Sandbox Code Playgroud)

它可以处理任意数量的迭代,并且在这个意义上比嵌套for循环更通用.