如何比较两个列表中的项目Python 3.3 [英] How To Compare Items In Two Lists Python 3.3
问题描述
我尝试使用 cmp(list1,list2)
来了解它在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))
示例:
>>>len(set(['cat','dog','pup']) & set(['rat','cat','wolf']))
1
>>>set(['cat','dog','pup']) & set(['rat','cat','wolf'])
{'cat'}
或者,如果您由于某些原因不想使用集,则可以始终使用 collections.Counter
,它支持大多数多集操作:
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']
这篇关于如何比较两个列表中的项目Python 3.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!