擅长:python、mysql、java
<p>你就不能像你描述的那样直接做吗:</p>
<pre class="lang-py prettyprint-override"><code>def foo(i, a, b):
for el in i:
if el in a:
a.remove(el)
else:
b.add(el)
</code></pre>
<p>我不会在适当的地方对a和b进行变异,特别是因为它们是作为函数的参数提供的,所以安全的版本应该是</p>
<pre class="lang-py prettyprint-override"><code>def foo(i, a, b):
a_new = a.copy()
b_new = b.copy()
for el in i:
if el in a:
a_new.remove(el)
else:
b_new.add(el)
return a_new, b_new
</code></pre>
<p>在一般情况下,它会更有效,因为<code>i</code>是一个iterable(可能是一个实际的迭代器),您只需对它迭代一次。如果您将它转换为一个集合,那么在内部它将被迭代一次,然后对于每个集合操作,至少重复两次</p>
<p>您还可以像这样使用来自<code>itertools</code>的<code>groupby</code>:</p>
<pre class="lang-py prettyprint-override"><code>from itertools import groupby
def foo(i, a, b):
for in_a, i_group in groupby(i, key=lambda x: x in a):
if in_a:
a -= set(i_group)
else:
b |= set(i_group)
</code></pre>