Intersection of two Counters

隐身守侯 提交于 2019-12-05 05:40:52

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.

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.

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