[英]Sets intersection with returning every match
everyone!每个人!
I'm looking for most elegant way to find intersection of two sets, but I need to get a every match of keys我正在寻找最优雅的方法来找到两组的交集,但我需要获得每一个匹配的键
The examples of what I mean:我的意思的例子:
s1 = {1, 1, 2, 3}
s2 = {4, 5, 1, 1}
s1.intersection(s2)
Output is: Output 是:
{1}
What output I need:我需要什么 output:
{1, 1}
Thank you everyone for help and sorry for my english谢谢大家的帮助,对不起我的英语
If you want a set-like thing for which items can appear with multiplicity greater than 1, then you could use a multiset .如果你想要一个类似集合的东西,其中的项目可以以大于 1 的重数出现,那么你可以使用multiset 。 These can be represented by Counter
objects.这些可以由Counter
对象表示。 There is no built-in intersection method for those, but you could write a function which computes it by taking the min of two counts:这些没有内置的交集方法,但你可以编写一个 function 来计算它,取两个计数的最小值:
from collections import Counter
def intersection(s1,s2):
'''intersection of multisets s1,s2'''
d = {}
for i in s1:
c = min(s1[i],s2[i])
if c > 0:
d[i] = c
return Counter(d)
#test:
s1 = Counter([1, 1, 2, 3])
s2 = Counter([4, 5, 1, 1])
print(s1)
print(s2)
print(intersection(s1,s2))
Output: Output:
Counter({1: 2, 2: 1, 3: 1})
Counter({1: 2, 4: 1, 5: 1})
Counter({1: 2})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.