2010-03-23 5 views
4

에서 동일한 요소의 수를 찾을 수 있습니다. 경우에 그것은 내가 중첩 루프를 할 만하지만, 상기는 array_intersect 기능을 PHP에서 같은 기능에는 2 개에는 파이썬에서

감사

+0

중복 : http://stackoverflow.com/questions/2424700/how-to-get-a-list-with-elements-that-are-contained-in -two-other-lists –

답변

9

를 내장이 없을 수 알 2 (C와 D)

을 것에 대해 당신의 교집합을 사용할 수 :

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 
관련 문제