简体   繁体   English

Python-将两个元组列表合并为一个元组列表

[英]Python - merge two lists of tuples into one list of tuples

What's the pythonic way of achieving the following? 实现以下目标的Python方法是什么?

from: 从:

a = [('apple', 10), ('of', 10)]
b = [('orange', 10), ('of', 7)]

to get 要得到

c = [('orange', 10), ('of', 17), ('apple', 10)]

You essentially have word-counter pairs. 您基本上有字计数器对。 Using collections.Counter() lets you handle those in a natural, Pythonic way: 使用collections.Counter()可让您以自然的Python方式处理它们:

from collections import Counter

c = (Counter(dict(a)) + Counter(dict(b))).items()

Also see Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? 另请参阅是否有任何Python方法将两个字典组合在一起(为同时出现在两个字典中的键添加值)?

Demo: 演示:

>>> from collections import Counter
>>> a = [('apple', 10), ('of', 10)]
>>> b = [('orange', 10), ('of', 7)]
>>> Counter(dict(a)) + Counter(dict(b))
Counter({'of': 17, 'orange': 10, 'apple': 10})
>>> (Counter(dict(a)) + Counter(dict(b))).items()
[('orange', 10), ('of', 17), ('apple', 10)]

You could just drop the .items() call and keep using a Counter() here. 您可以只删除.items()调用并在此处继续使用Counter()

You may want to avoid building (word, count) tuples to begin with and work with Counter() objects from the start. 您可能要避免从一开始就构建(单词,计数)元组,并从一开始就使用Counter()对象。

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

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