两个列表中的共同元素,其中元素是相同的

时间:2013-07-20 12:56:58

标签: python list intersection

我有两个列表如下:

a=['not','not','not','not']
b=['not','not']

我必须找到包含上面两个列表的intesection的列表的len,结果是:

intersection=['not','not']
len(intersection)
2

现在的问题是我已经尝试了filter(lambda x: x in a,b)filter (lambda x: x in b,a),但当两个中的一个比另一个更长时,我没有得到一个交集,而只是一个成员资格检查。在上面的例子中,由于a的所有成员都在b中,因此我获得了4个公共元素的len;我想要的是交叉点,即len 2。 使用set().intersection(set())会创建一个集合,这不是我想要的,因为所有元素都是相同的。 您能否为我提出任何有价值且紧凑的解决方案?

4 个答案:

答案 0 :(得分:1)

如果您不介意使用collections.Counter,那么您可以使用

之类的解决方案
>>> import collections
>>> a=['not','not','not','not']
>>> b=['not','not']

>>> c1 = collections.Counter(a)
>>> c2 = collections.Counter(b)

然后通过'not'索引

>>> c1['not'] + c2['not']
6

对于十字路口,您需要

>>> (c1 & c2) ['not']
2

答案 1 :(得分:0)

我没有看到任何特别紧凑的计算方法。我们先来看看 解决方案吧。

intersection是较短列表的一些子列表(例如b)。现在,为了在较短列表不是非常短的情况下获得更好的性能,请将较长的列表设为一组(例如set(a))。然后可以将交集表示为较短列表中那些也在较长集合中的项目的列表理解:

def common_elements(a, b):
    shorter, longer = (a, b) if len(a)<len(b) else (b, a)
    longer = set(longer)
    intersection = [item for item in shorter if item in longer]
    return intersection

a = ['not','not','not','not']
b = ['not','not']
print(common_elements(a,b))

答案 2 :(得分:0)

set执行。首先将这些列表设置为集合然后进行交集。现在交叉路口可能会有重复。因此,对于交叉点中的每个元素,请在ab中进行最小重复。

>>> a=['not','not','not','not']
>>> b=['not','not']
>>> def myIntersection(A,B):
...     setIn = set(A).intersection(set(B))
...     rt = []
...     for i in setIn:
...         for j in range(min(A.count(i),B.count(i))):
...             rt.append(i)
...     return rt
...
>>> myIntersection(a,b)
['not', 'not']

答案 3 :(得分:0)

您是否考虑过以下方法?

a = ['not','not','not','not']
b = ['not','not']

min(len(a), len(b))
# 2

由于所有元素都相同,因此公共元素的数量只是两个列表长度的最小值。

相关问题