a = [1, 2, 9, 5, 1]
b = [9, 8, 7, 6, 5]
我想计算两个列表之间的重复项数。因此,使用上面的代码,我想返回计数 2,因为 9 和 5 对于两个列表都是通用的。
我试过类似的方法,但效果不佳。
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
为什么您的代码不起作用:
>>> def filter_(x, y):
... count = 0
... for num in y:
... if num in x:
... count += 1
... return count
...
>>> filter_(a, b)
2
您的返回计数
在 for 循环内并且它在执行未完成的情况下返回。
关于python - 计算 2 个列表之间的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4775004/