两个列表之间的公共元素未在Python中使用集 [英] Common elements between two lists not using sets in Python

查看:88
本文介绍了两个列表之间的公共元素未在Python中使用集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算两个列表的相同元素.列表可以包含重复的元素,因此我无法将其转换为集合并使用&运算符.

I want count the same elements of two lists. Lists can have duplicate elements, so I can't convert this to sets and use & operator.

a=[2,2,1,1]
b=[1,1,3,3]

设置(a)&设置(b)工作
& b不起作用

set(a) & set(b) work
a & b don't work

有可能做到这一点而又不拘一格?

It is possible to do it withoud set and dictonary?

推荐答案

在Python 3.x(和Python 2.7,发布时)中,您可以使用

In Python 3.x (and Python 2.7, when it's released), you can use collections.Counter for this:

>>> from collections import Counter
>>> list((Counter([2,2,1,1]) & Counter([1,3,3,1])).elements())
[1, 1]

这是使用 collections.defaultdict 的替代方法(在Python 2.5中可用然后).它具有很好的属性,即结果的顺序是确定性的(它基本上与第二个列表的顺序相对应).

Here's an alternative using collections.defaultdict (available in Python 2.5 and later). It has the nice property that the order of the result is deterministic (it essentially corresponds to the order of the second list).

from collections import defaultdict

def list_intersection(list1, list2):
    bag = defaultdict(int)
    for elt in list1:
        bag[elt] += 1

    result = []
    for elt in list2:
        if elt in bag:
            # remove elt from bag, making sure
            # that bag counts are kept positive
            if bag[elt] == 1:
                del bag[elt]
            else:
                bag[elt] -= 1
            result.append(elt)

    return result

对于这两种解决方案,输出列表中任何给定元素x的出现次数都是两个输入列表中x的出现次数的最小值.从您的问题尚不清楚这是否是您想要的行为.

For both these solutions, the number of occurrences of any given element x in the output list is the minimum of the numbers of occurrences of x in the two input lists. It's not clear from your question whether this is the behavior that you want.

这篇关于两个列表之间的公共元素未在Python中使用集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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