在Python中查找2个列表中相同元素的数量

时间:2010-03-23 13:17:41

标签: python arrays array-intersect

在Python中如果我有2个列表说:

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']

有没有办法找出他们有多少元素相同。在这种情况下,它将是2(c和d)

我知道我可以做一个嵌套循环但是没有内置函数,就像php中的array_intersect函数一样

由于

4 个答案:

答案 0 :(得分:10)

您可以使用集合交集:)

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']
set(l1).intersection(l2)
set(['c', 'd'])

答案 1 :(得分:6)

>>> l1 = ['a', 'b', 'c', 'd']
>>> l2 = ['c', 'd', 'e']
>>> set(l1) & set(l2)
set(['c', 'd'])

答案 2 :(得分:5)

如果您只有唯一元素,则可以使用set数据类型并使用intersection:

s1, s2 = set(l1), set(l2)
num = len(s1.intersection(s2))

答案 3 :(得分:1)

使用集合:

l1 = ['a', 'b', 'c', 'd']
l2 = ['c', 'd', 'e']


def list_count_common(list_a, list_b):
    result = len(list(set(list_a) & set(list_b))) ## this is the line that does what you want
    return result

print list_count_common(l1, l2) ## prints 2