我正在努力寻找如何做到这一点;也许有一个我不知道的关于这个集合操作的词。
我有几个具有重叠元素的集合,我想找到每个给定集合中哪些元素是唯一的。例如:
sets = {
'rat': {'a', 'b', 'c', 'd'},
'cat': {'a', 'b', 'd', 'f'},
'dog': {'a', 'b'},
}
我可以看到 f 是 cats 所独有的,而 c 是 rats 所独有的。所以我想做一些集合操作或其他操作来生成该数据:
uniq = {
'rat': {'c'},
'cat': {'f'},
'dog': set(),
}
(额外的问题,主要是出于好奇——而不是集合,如果我将它们放入 pandas / numpy 2d 矩阵中,是否有一种简洁的方法来执行相同的操作?例如,其中 'rat', 'cat', ' dog' 是列,a,b,c,... 是行,反之亦然)
from collections import Counter
sets = {
'rat': {'a', 'b', 'c', 'd'},
'cat': {'a', 'b', 'd', 'f'},
'dog': {'a', 'b'},
}
ctr = Counter()
for s in sets.values():
ctr.update(s)
uniq = {
k: {x for x in v if ctr[x] == 1}
for k, v in sets.items()
}
print(uniq)