本文介绍了计算2个列表之间的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a = [1, 2, 9, 5, 1]
b = [9, 8, 7, 6, 5]
我想计算两个列表之间重复的次数.因此,使用上述方法,我想返回2的计数,因为两个列表共有9和5.
I want to count the number of duplicates between the two lists. So using the above, I want to return a count of 2 because 9 and 5 are common to both lists.
我尝试了类似的方法,但是效果不佳.
I tried something like this but it didn't quite work.
def filter_(x, y):
count = 0
for num in y:
if num in x:
count += 1
return count
推荐答案
更好的方法:
>>> a = [1, 2, 9, 5, 1]
>>> b = [9, 8, 7, 6, 5]
>>> len(set(a) & set(b)) # & is intersection - elements common to both
2
为什么您的代码不起作用:
Why your code doesn't work:
>>> def filter_(x, y):
... count = 0
... for num in y:
... if num in x:
... count += 1
... return count
...
>>> filter_(a, b)
2
您的返回计数
在for循环内,并且返回时未完成执行.
Your return count
was inside the for loop and it returned without execution being complete.
这篇关于计算2个列表之间的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!