1

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 keywords with list 1 and 2 separately. so it would become:

EDIT

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

What if i had more than 10 lists? <-- optional question.

5
  • 'I' is not in list2, does it still belong in common? Commented Feb 26, 2012 at 6:22
  • Yes, It doesn't have to be in all 3 lists. Commented Feb 26, 2012 at 6:24
  • See my answer which should give you the result you are looking for (although possibly with a different ordering for common). Commented Feb 26, 2012 at 6:57
  • F.J, im testing it now. i'll probably be back in 5 minutes :) Commented Feb 26, 2012 at 7:04
  • Just edited my answer since you revised common to no longer include 'Oh'. Commented Feb 26, 2012 at 7:14

3 Answers 3

3

Probably using a set.

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

However, you may need to define what you mean by "the words in common from each list", because the words you listed are only common to two of the lists you showed.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, I suspect you do want to use sets in any case. Try just print list(set(list1) & set(list2)) and see what happens.
2

You could convert them to sets then do an intersection:

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

Comments

0

Since your comment indicates that you want items that exist in both Keyword and either list1 or list2, you probably don't want an intersection of all three. Instead you should get the union of list1 and list2, and then get the intersection of that 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))

1 Comment

set.union accepts *args, so there is no reason to invoke reduce. It's also possible to feed lists to union and have them set-ified on demand, which may be a little faster and is certainly simpler. All you need is common = list(set().union(*lists) & set(Keyword)), or equivalently common = list(set().union(*lists).intersection(Keyword))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.