问题
I tried using cmp(list1, list2)
to learn it's no longer supported in Python 3.3. I've tried many other complex approaches, but none have worked.
I have two lists of which both contain just words and I want it to check to see how many words feature in both and return the number for how many.
回答1:
You can find the length of the set intersection using &
like this:
len(set(list1) & set(list2))
Example:
>>>len(set(['cat','dog','pup']) & set(['rat','cat','wolf']))
1
>>>set(['cat','dog','pup']) & set(['rat','cat','wolf'])
{'cat'}
Alternatively, if you don't want to use sets for some reason, you can always use collections.Counter, which supports most multiset operations:
>>> from collections import Counter
>>> print(list((Counter(['cat','dog','wolf']) & Counter(['pig','fish','cat'])).elements()))
['cat']
回答2:
If you just want the count of how many words are common
common = sum(1 for i in list1 if i in list2)
If you actually want to get a list of the shared words
common_words = set(list1).intersection(list2)
来源:https://stackoverflow.com/questions/29210210/how-to-compare-items-in-two-lists-python-3-3