擅长:python、mysql、java
<p>在Python3.x(以及Python2.7发布时)中,可以使用<a href="http://docs.python.org/dev/library/collections.html#collections.Counter" rel="noreferrer">collections.Counter</a>来完成以下操作:</p>
<pre><code>>>> from collections import Counter
>>> list((Counter([2,2,1,1]) & Counter([1,3,3,1])).elements())
[1, 1]
</code></pre>
<p>这里有一个使用<a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="noreferrer">collections.defaultdict</a>(在Python 2.5和更高版本中提供)的替代方法。它有一个很好的特性,即结果的顺序是确定的(它本质上对应于第二个列表的顺序)。</p>
<pre><code>from collections import defaultdict
def list_intersection(list1, list2):
bag = defaultdict(int)
for elt in list1:
bag[elt] += 1
result = []
for elt in list2:
if elt in bag:
# remove elt from bag, making sure
# that bag counts are kept positive
if bag[elt] == 1:
del bag[elt]
else:
bag[elt] -= 1
result.append(elt)
return result
</code></pre>
<p>对于这两种解决方案,输出列表中任何给定元素<code>x</code>的出现次数是两个输入列表中<code>x</code>出现次数的最小值。你的问题不清楚这是否是你想要的行为。</p>