简体   繁体   中英

How To Compare Items In Two Lists Python 3.3

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.

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']

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM