计算 2 个列表之间的重复项 [英] Count duplicates between 2 lists

查看:23
本文介绍了计算 2 个列表之间的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = [1, 2, 9, 5, 1]b = [9, 8, 7, 6, 5]

我想计算两个列表之间重复的次数.因此,使用上述内容,我想返回 2 的计数,因为 9 和 5 对两个列表都是通用的.

我尝试过类似的方法,但效果不佳.

def filter_(x, y):计数 = 0对于 y 中的 num:如果 num 在 x:计数 += 1返回计数

解决方案

更短更好:

<预><代码>>>>a = [1, 2, 9, 5, 1]>>>b = [9, 8, 7, 6, 5]>>>len(set(a) & set(b)) # &是交集 - 两者共有的元素2

为什么您的代码不起作用:

<预><代码>>>>定义过滤器_(x,y):...计数= 0... 对于 y 中的 num:...如果在 x 中为 num:...计数+= 1...返回计数...>>>过滤器_(a, b)2

您的 return count 在 for 循环内,它在没有执行完成的情况下返回.

a = [1, 2, 9, 5, 1]
b = [9, 8, 7, 6, 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

解决方案

Shorter way and better:

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

Your return count was inside the for loop and it returned without execution being complete.

这篇关于计算 2 个列表之间的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆