Intersection of two Counters

二次信任 提交于 2020-01-13 08:52:10

问题


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]

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])

But perhaps there is an easier (or faster) way?


回答1:


Use & for intersection:

>>> Counter(a) & Counter(b)
Counter({1: 2, 3: 1, 5: 1, 7: 1})

From docs:

Intersection(&) and union(|) return the minimum and maximum of corresponding counts.




回答2:


Instead of

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[k], cnts_b[k])

use

cnts_a_b = cnts_a & cnts_b

as & means the intersection of the Counter objects.



来源:https://stackoverflow.com/questions/44012479/intersection-of-two-counters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!