在python中合并嵌套的for循环 [英] Combine nested for loops in python
本文介绍了在python中合并嵌套的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下形式的嵌套循环:
Suppose I have a nested loop of the form:
for i in List1:
for j in List2:
DoSomething(i,j)
可以按照以下步骤进行操作吗:
Can it be done as follows:
for i,j in combine(List1, List2):
DoSomething(i,j)
预先感谢
因此要弄清楚Combine函数将执行以下操作:
So to clarify the combine function would do something as follows:
List1 = range(5)
List2 = range(5)
combine(List1, List2,)
>>> (0,0)
>>> (0,1)
>>> (0,2)
.
.
.
>>> (2,4)
>>> (3,0)
.
.
.
itertools.product完美运行
The itertools.product works perfectly
推荐答案
您可以使用itertools.product
import itertools
for i,j in itertools.product(List1, List2):
DoSomething(i,j)
这篇关于在python中合并嵌套的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文