[英]Python - merge two lists of tuples into one list of tuples
实现以下目标的Python方法是什么?
从:
a = [('apple', 10), ('of', 10)]
b = [('orange', 10), ('of', 7)]
要得到
c = [('orange', 10), ('of', 17), ('apple', 10)]
您基本上有字计数器对。 使用collections.Counter()
可让您以自然的Python方式处理它们:
from collections import Counter
c = (Counter(dict(a)) + Counter(dict(b))).items()
另请参阅是否有任何Python方法将两个字典组合在一起(为同时出现在两个字典中的键添加值)?
演示:
>>> 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)]
您可以只删除.items()
调用并在此处继续使用Counter()
。
您可能要避免从一开始就构建(单词,计数)元组,并从一开始就使用Counter()
对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.