【发布时间】:2021-11-02 04:06:16
【问题描述】:
假设有三个排序列表,A、B、C。
A = [1, 2, 3, 4]
B = [3, 4, 5]
C = [2, 3, 4]
我正在使用itertools.product 查找总和小于 10 的所有可能组合。
如果我只有三个列表,我将使用以下代码。
A = [1, 2, 3, 4] B = [3, 4, 5] C = [2, 3, 4]
for a in A:
for b in B:
for c in C:
if a + b + c < 10:
print(a, b, c)
else:
break
这里,每个列表都是排序的,因此我使用 break 来提高效率。
但是当我使用itertools.product 时,那我如何使用break 呢? 我的意思是如何直接进行特定的迭代(例如,a = 3,b = 3,c = 3)?
for a, b, c in itertools.product(A, B, C):
....?
【问题讨论】:
-
使用
continue跳到下一个迭代。 -
@ddejohn 我认为这不是 OP 想要的。他/她想跳过多次迭代。
-
啊,我现在明白了。 OP,使用
itertools.product做你想做的事是不可能的。
标签: python for-loop iteration itertools