2016-06-29 2 views
-2

파이썬 2.6을 사용하여 본질적으로리스트의리스트를 가지고 있습니다. 일부 개체는 하나 이상의 목록에서 동일합니다.파이썬에서 여러리스트에 포함 된 객체의 목록을 얻는 방법

모든 목록에 포함 된 개체 목록을 가져와야합니다. 예를 들어

:

list1 = ['apple','pear','cheese','grape'] 
list2 = ['grape','carrot','pear','cheese'] 
list3 = ['apple','cheese','grape'] 

결과 목록들이 3 개 목록에있는 유일한 객체이기 때문에

['grape','cheese'] 

을 할 필요가있다.

도움 주셔서 감사합니다.

list(set(list1) & set(list2) & set(list3)) 
+0

당신은 첫째로 연역적 알고리즘을 배울 수 있습니다. https://en.wikipedia.org/wiki/Apriori_algorithm – Windyground

+1

1 단계 코드를 작성합니다. – IanAuld

+0

아마도'set' 내장 클래스를 사용하고 싶을 것입니다. 그러나 세트에는 고유 한 항목 만 포함되어 있으며 목록에는 "동일한"항목의 배수가있을 수 있습니다. 그것은 당신이 정말로 무엇을 확신해야한다는 것을 의미합니다. – uchuugaka

답변

1

는이 같은 set 연산자를 사용할 수 있습니다 :

['grape', 'cheese'] 

당신이 단어는이 작업을 수행 할 수 있습니다 알파벳 순으로 정렬하려면 :

print(sorted(set(list1) & set(list2) & set(list3))) 

출력 : 어떻게 이런 일에 대한

['cheese', 'grape'] 
1

당신은 sets

list1 = ['apple','pear','cheese','grape'] 
list2 = ['grape','carrot','pear','cheese'] 
list3 = ['apple','cheese','grape'] 

print(list(set(list1) & set(list2) & set(list3))) 

출력을 사용할 수 있습니다 : 당신이 출력으로 당신이 할 수있는 list를 원하는 경우

set(list1) & set(list2) & set(list3) 

:

2
from collections import Counter 

a = Counter(list1+list2+list3) 

print([x for x in a if a[x]==3]) 
+0

'all()'은 내장 함수이므로 덮어 쓰지 않습니다. 또한 3 개의 목록이 있고 각 문자열이 각 목록에 한 번만 나타나는 경우에만 작동합니다 (OP에는 중복이 문제가되지 않는다고 언급되지 않았습니다). – IanAuld

0

?

a = [1,2,3,4,8] 
b = [4,5,6,7,8] 
c = [4,8,9] 

print(list(set(a).intersection(b).intersection(c))) 

이 코드에 더 가독성을 추가하고 다른 당신이 뭘 하려는지 알이 코드를 사용하려고하는 사람으로서 나는() 교차로를 사용하고 있습니다.

1

사용 설정 및 설정 교차로 :

>>> list1 = ['apple','pear','cheese','grape'] 
>>> list2 = ['grape','carrot','pear','cheese'] 
>>> list3 = ['apple','cheese','grape'] 
>>> list_of_lists = [list1,list2,list3] 
>>> reduce(set.intersection,map(set,list_of_lists)) 
set(['cheese', 'grape']) 
1

set 클래스를 사용하십니까, 그것은 오일러 설정처럼 반복 가능 객체처럼 조작 할 수 있습니다 intersection 같은 유용한 방법이있다.

list1 = ['apple', 'pear', 'cheese', 'grape'] 
list2 = ['grape', 'carrot', 'pear', 'cheese'] 
list3 = ['apple', 'cheese', 'grape'] 
print set(list1) & set(list2) & set(list3) 

이 설정된 개체를 반환하지만 목록을 원하는 경우 바로 list() 방법을 사용합니다 : 여기 개념의 증거와 질문에 대한 답변입니다.

유용하게 사용할 수 있거나 새로운 것을 배울 수 있기를 바랍니다.

현재 세트에 위로 읽어야 https://docs.python.org/2/library/stdtypes.html#set

관련 문제