包括重复项在内的两个列表的交集? [英] Intersection of two lists including duplicates?

查看:37
本文介绍了包括重复项在内的两个列表的交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>a = [1,1,1,2,3,4,4]>>>b = [1,1,2,3,3,3,4][1,1,2,3,4]

请注意,这与这个问题不同:保持重复的两个列表的 Python 交集因为即使列表 a 中有三个 1,列表 b 中也只有两个,所以结果应该只有两个.

解决方案

您可以使用 collections.Counter 用于此,当您进行交集时,它将为每个元素提供在任一列表中找到的最低计数.

from collections import Counterc = list((Counter(a) & Counter(b)).elements())

输出:

[1, 1, 2, 3, 4]

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

[1,1,2,3,4]

Please note this is not the same question as this: Python intersection of two lists keeping duplicates Because even though there are three 1s in list a, there are only two in list b so the result should only have two.

解决方案

You can use collections.Counter for this, which will provide the lowest count found in either list for each element when you take the intersection.

from collections import Counter

c = list((Counter(a) & Counter(b)).elements())

Outputs:

[1, 1, 2, 3, 4]

这篇关于包括重复项在内的两个列表的交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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