English 中文(简体)
2个清单之间的数字重复
原标题:Count duplicates between 2 lists
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 

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

页: 1

问题回答

您可使用set.intersection :

>>> set(a).intersection(set(b)) # or just: set(a).intersection(b)
set([9, 5])

或者,对于交叉点的长度:

>>> len(set(a).intersection(set(b)))
2

或更简洁:

>>> len(set(a) & set(b))
2

如果你想看到多彩的条目,基于解决办法就会失败;你们需要像样的东西。

from collections import Counter

def numDups(a, b):
    if len(a)>len(b):
        a,b = b,a

    a_count = Counter(a)
    b_count = Counter(b)

    return sum(min(b_count[ak], av) for ak,av in a_count.iteritems())

之后

numDups([1,1,2,3], [1,1,1,1,1])

回返 2. 本比额表的运行时间为O(n+m)。

此外,您的初步解决办法

for num in y:
    if num in x:
        count += 1

错误——适用于[1,2,3,3]和[1,1,1,1,1,1,1,3],你的代码将退回3或6,neither,其中正确(回答应为2)。

将其转换成<条码>。

 len(set(a).intersection(set(b)))

以下解决办法还涉及清单中的重复内容:

from collections import Counter

def number_of_duplicates(list_a, list_b):
    count_a = Counter(list_a)
    count_b = Counter(list_b)

    common_keys = set(count_a.keys()).intersection(count_b.keys())
    return sum(min(count_a[key], count_b[key]) for key in common_keys)

number_of_duplicates ([1, 2, 2, 2, 3], [1, 2, 2, 4] results in the expected 3.


请注意,@Hugh bothwell也提供了类似的解决办法,但是,如果某一要素只包含在较短的清单中,则有时会扔下<条码>。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...