我确实有以下n=3列表(嵌套循环)我需要它是通用的,并适用于任何n个列表
object1 = [4, 5, 3]
object2 = [1, 2, 3, 4]
object3 = [1, 0]
for c1 in object1:
for c2 in object2:
for c3 in object3:
if c1+c2+c3<9:
print(c1,c2,c3)
如何在Python中高效地完成?
您需要itertools.product
:
import itertools
for cs in itertools.product(*[object1, object2, object3]):
if sum(cs) < 9:
print(cs[0], cs[1], cs[2])
# OR
# for c1, c2, c3 in itertools.product(*[object1, object2, object3]):
# if (c1+c2+c3) < 9:
# print(c1,c2,c3)
输出:
4 1 1
4 1 0
4 2 1
4 2 0
4 3 1
4 3 0
4 4 0
5 1 1
5 1 0
5 2 1
5 2 0
5 3 0
3 1 1
3 1 0
3 2 1
3 2 0
3 3 1
3 3 0
3 4 1
3 4 0