a = [1]
b = [2,3]
c = [4,5,6]
d = [a,b,c]
for x0 in d[0]:
for x1 in d[1]:
for x2 in d[2]:
print(x0,x1,x2)
结果:
1 2 4
1 2 5
1 2 6
1 3 4
1 3 5
1 3 6
完美,现在我的问题是如何定义它的功能,考虑到当然可能有更多带有值的列表。这个想法是获取功能,这将动态地产生相同的结果。
有没有办法向python解释:“例如做8个嵌套循环”?
最佳答案
您可以使用 itertools
为您计算产品,可以使用 *
运算符将您的列表转换为 itertools.product()
的参数功能。
import itertools
a = [1]
b = [2,3]
c = [4,5,6]
args = [a,b,c]
for combination in itertools.product(*args):
print combination
输出是
(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)
关于function - 如何定义动态嵌套循环python函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276007/