找到“重叠"在2个python列表之间 [英] find the "overlap" between 2 python lists

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

问题描述

给出2个列表:

a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]

我想找到重叠":

c = [3,4,5,5,6]

如果我可以提取a和b中不在c中的部分的余数",我也会很喜欢.

I'd also like it if i could extract the "remainder" the part of a and b that's not in c.

a_remainder = [5,]
b_remainder = [1,4,7,]

注意: a中有3个5,b中有2个. b有两个4,而a有一个.

Note: a has three 5's in it and b has two. b has two 4's in it and a has one.

结果列表c应该有两个5(由列表b限制)和一个4(由列表a限制).

The resultant list c should have two 5's (limited by list b) and one 4 (limited by list a).

这给了我我想要的东西,但我不禁想到还有更好的方法.

This gives me what i want, but I can't help but think there's a much better way.

import copy

a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]

c = []
for elem in copy.deepcopy(a):
    if elem in b:
        a.pop(a.index(elem))
        c.append(b.pop(b.index(elem)))

# now a and b both contain the "remainders" and c contains the "overlap"

另一方面,我要问的名字比重叠"和余数"更准确的名字是什么?

On another note, what is a more accurate name for what I'm asking for than "overlap" and "remainder"?

推荐答案

collection.Counter可用于实现完全满足您需要的多集.

collection.Counter available in Python 2.7 can be used to implement multisets that do exactly what you want.

a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]

a_multiset = collections.Counter(a)
b_multiset = collections.Counter(b)

overlap = list((a_multiset & b_multiset).elements())
a_remainder = list((a_multiset - b_multiset).elements())
b_remainder = list((b_multiset - a_multiset).elements())

print overlap, a_remainder, b_remainder

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

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