How To Compare Items In Two Lists Python 3.3

爷,独闯天下 提交于 2020-01-30 08:08:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!