两个柜台的交集 [英] Intersection of two Counters
本文介绍了两个柜台的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找两个列表之间的共享元素(以及共享的出现次数)。例如,这两个列表的交集:
I'm trying to find the shared elements (and the shared number of occurrences) between two lists. For example, the intersection of these two lists:
a = [1, 1, 2, 3, 4, 5, 6, 7, 8, 1]
b = [1, 1, 3, 5, 7, 9]
应返回 Counter({1:2,3:1、5:1、7:1})
或类似的内容,例如 {1:2、3:1、5:1、7:1}
或 [1、1、3、5、7]
(列表的顺序无关紧要)。
should return Counter({1: 2, 3: 1, 5: 1, 7: 1})
or something similar, e.g. {1: 2, 3: 1, 5: 1, 7: 1}
or [1, 1, 3, 5, 7]
(order of the list doesn't matter).
我已经有一种有效的方法:
I already have an approach that works:
cnts_a = Counter(a)
cnts_b = Counter(b)
cnts_a_b = Counter() # counter for the shared values
for key in set(cnts_a).intersection(cnts_b):
cnts_a_b[key] = min(cnts_a[key], cnts_b[key])
但也许
推荐答案
使用&
进行交集:
>>> Counter(a) & Counter(b)
Counter({1: 2, 3: 1, 5: 1, 7: 1})
来自文档:
交集(
&
)和union(|
)返回相应计数的最小和最大。
Intersection(
&
) and union(|
) return the minimum and maximum of corresponding counts.
这篇关于两个柜台的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文