擅长:python、mysql、java
<p>如果您只想在达到某个条件后中止分配,并且希望避免从笛卡尔积中为这些条件生成所有元素,那么首先就不要列出所有组合</p>
<p><code>itertools.product</code>是<em>lazy</em>,这意味着它一次只生成笛卡尔积的一个值。所以你不需要生成所有的元素,也不需要比较元素。只是不要对结果调用<code>list()</code>,因为这样会迭代整个序列并将所有可能的组合存储在内存中:</p>
<pre><code>allocations = product(*strategies.values())
for alloc in allocations:
PWC[alloc] = [a for (a,b) in zip(help,alloc) if coalitions[a] >= sum(b)]
# check whether you can stop looking at more values from the cartesian product
if someCondition(alloc):
break
</code></pre>
<p>重要的是要注意<code>itertools.product</code>是如何生成值的,它遵循什么模式。基本上相当于:</p>
<pre><code>for a in firstIterable:
for b in secondIterable:
for c in thirdIterable:
…
for n in nthIterable:
yield (a, b, c, …, n)
</code></pre>
<p>因此,从iterables的左侧可以得到一个递增的模式。因此,请确保您对iterables的排序方式能够正确指定中断条件</p>