在Python中组合嵌套的for循环

Iwa*_*ith 2 python loops

假设我有一个以下形式的嵌套循环:

for i in List1:
    for j in List2:
        DoSomething(i,j)
Run Code Online (Sandbox Code Playgroud)

是否可以按如下方式进行:

for i,j in combine(List1, List2):
    DoSomething(i,j)
Run Code Online (Sandbox Code Playgroud)

提前致谢

因此,为了澄清组合函数将执行以下操作:

List1 = range(5)
List2 = range(5)
combine(List1, List2,)
>>> (0,0)
>>> (0,1)
>>> (0,2)
.
.
.
>>> (2,4)
>>> (3,0)
.
.
.
Run Code Online (Sandbox Code Playgroud)

itertools.product 工作完美

Cor*_*mer 5

您可以使用itertools.product

import itertools
for i,j in itertools.product(List1, List2):
    DoSomething(i,j)
Run Code Online (Sandbox Code Playgroud)