擅长:python、mysql、java
<p>既然你说</p>
<blockquote>
<p>Iterating through and removing items is not viable as this needs to
scale to very large sizes.</p>
</blockquote>
<p>最好是包装<code>permutations</code>生成的interator,它将生成您想要的元组,并跳过您不想要的元组:</p>
<pre><code>my_list = [1,2,3,4]
def my_perms(my_list, f):
for e in permutations(my_list):
if f(e):
yield e
>>> list(my_perms(my_list, lambda t: t[:2] not in {(4,1), (3,1)}))
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
</code></pre>
<p>或者,使用<a href="https://docs.python.org/2/library/itertools.html#itertools.ifilter" rel="nofollow">ifilter from itertools</a>:</p>
<pre><code>>>> list(ifilter(lambda t: t[:2] not in {(4,1), (3,1)}, permutations(my_list)))
</code></pre>
<p>或者,直接在python3+上进行过滤,因为这也会创建一个迭代器,而不是像python2上的过滤器那样创建一个列表。你知道吗</p>