[英]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.