Python Checking Multiple Lists for Similarities

For example, I have 3 lists

list1=['Oh','My','god','I','A','List!'] list2=['Oh','What','You','Dramatic?'] Keyword=['I','Dunno','What','You','Talking','About','DOT'] 

EDIT

I want to compare the keywords with list 1 and 2 separately. therefore it will be as follows:

EDIT

 common=['What','I','You'] 

What if I had more than 10 lists? <is an optional question.

0
source share
3 answers

Since your comment indicates that you need elements that exist in both Keyword and either list1 or list2 , you probably don't want the intersection of all three. Instead, you should get the union of list1 and list2 , and then get the intersection of this result and Keyword .

Something like the following should give you what you want:

 common = list((set(list1) | set(list2)) & set(Keyword)) 

Or an alternative approach that is more extensible (thanks to Karl for the shortened version):

 lists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10] common = list(set().union(*lists).intersection(Keyword)) 
0
source

Perhaps using set .

 common = list(set(list1) & set(list2) & set(Keyword)) 

However, you may need to define what you mean by โ€œcommon words from each list,โ€ since the words you listed are common to the two lists you have indicated.

+3
source

You can convert them to sets and then cross:

 intersect = list(set(list1) & set(list2)) & set(Keyword)) 
+2
source

Source: https://habr.com/ru/post/1483342/


All Articles