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

查看:12
本文介绍了两个列表之间的公共元素不使用 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]

set(a) &设置(b)工作
一个&b 不工作

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

没有set和dictionary也可以吗?

It is possible to do it withoud set and dictonary?

推荐答案

在 Python 3.x(和 Python 2.7,当它发布时),你可以使用 collections.Counter 为此:

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天全站免登陆