开发者

in Python find number of same elements in 2 lists

In Python if I have 2 lists say:

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

is there a way to find out how many elements they开发者_JAVA百科 have the same. In the case about it would be 2 (c and d)

I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function

Thanks


You can use a set intersection for that :)

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


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


If you only have unique elements, you can use the set data type and use intersection:

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


Using sets:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜