简体   繁体   English

Python合并集部分

[英]Python merge sets partially

I have a set of tuples (set1), where each tuple is (somename1, somename2, Number).我有一组元组 (set1),其中每个元组是 (somename1, somename2, Number)。 Where number indicates the times we've seen somename1, somename2.其中 number 表示我们看到 somename1, somename2 的次数。 I want to merge it with a different set (set2) where somename1, somename2 might be in the set, and update Number accordingly.我想将它与另一个集合 (set2) 合并,其中 somename1、somename2 可能在集合中,并相应地更新 Number。 Right now, for obvious reasons, set1 & set2 returns an empty set.现在,出于显而易见的原因, set1 和 set2 返回一个空集。 How can I update set1 efficiently?如何有效地更新 set1?

Sample data = Set1 = {('soda','coca cola',5), ('chocolate','mars',13)}样本数据 = Set1 = {('soda','coca cola',5), ('chocolate','mars',13)}

You could use a Counter:您可以使用计数器:

>>> from collections import Counter
>>> Set1 = Counter({('soda','coca cola'): 5})
>>> Set2 = Counter({('soda','coca cola'): 3, ('chocolate','mars'): 10})
>>> Set1 + Set2
Counter({('soda', 'coca cola'): 8, ('chocolate', 'mars'): 10})

If you don't want to add keys from Set2 if they are not in Set1, you can use dict comprehension:如果您不想在 Set2 中添加不在 Set1 中的键,则可以使用 dict comprehension:

>>> Set1 = {('soda','coca cola'): 5}
>>> Set2 = {('soda','coca cola'): 3, ('chocolate','mars'): 10}
>>> {k: Set1[k] + Set2.get(k, 0) for k in Set1}

Here's an example if you want to use sets for input, and are just interested in the resulting data in any format (looks like I'm using defaultdict a lot lately):这是一个示例,如果您想使用集合进行输入,并且只对任何格式的结果数据感兴趣(看起来我最近经常使用defaultdict ):

from itertools import chain
from collections import defaultdict

s1 = set((
    ('a', 'b', 1), ('c', 'd', 2)
))
s2 = set((
    ('a', 'b', 2), ('c', 'd', 3), ('e', 'f', 4)
))

s3 = defaultdict(int)

for name1, name2, count in chain(s1, s2):
    s3[name1, name2] += count

for (name1, name2), total_count in s3.items():
    print(name1, name2, total_count)

Prints:印刷:

c d 5
e f 4
a b 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM