2010-03-23 41 views
4

在Python相同的元素個數,如果我有2只列出說:在Python找到2所列出

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

有沒有發現他們有多少元素具有相同的方式。在這種情況下它會是2(c和d)

我知道我可以做一個嵌套的循環,但不是有一個內置的功能就像在PHP與array_intersect功能

感謝

+0

重複:http://stackoverflow.com/questions/2424700/how-to-get-a-list-with-elements-that-are-contained-in - 兩個 - 其他 - 列表 – 2010-03-23 13:39:14

回答

9

您可以使用交集爲:)

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

如果你只有唯一的元素,你可以用一組數據類型和使用交集:

s1, s2 = set(l1), set(l2) 
num = len(s1.intersection(s2)) 
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