简体   繁体   中英

Python - merge two lists of tuples into one list of tuples

What's the pythonic way of achieving the following?

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:

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)?

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.

You may want to avoid building (word, count) tuples to begin with and work with Counter() objects from the start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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