简体   繁体   中英

merge list of tuples with sum values in Python

I have n lists of tuples that and should generate a list of final tuples by adding the values of the same keywords.

every tuple list has this form:

[('a1', 10), ('a2', 50), ('a3',5)]
[('s1', 10), ('a3', 50), ('s2',5)]

and I have to generate a list of tuples as follows

[('a1',10),('a2',50), ('a3',55), ('s1',10), ('s2',5)]

then I have to order it in a descending order and extract the x elements more frequently

as follow

[('a3',55), ('a2',50), ('a1',10), ('s1',10), ('s2',5)] #order list in descending order

# extract the 3 most frequently
[('a3',55), ('a2',50), ('a1',10)]

how can I do it?

thanks

from collections import Counter

lists = [
    [('a1', 10), ('a2', 50), ('a3',5)],
    [('s1', 10), ('a3', 50), ('s2',5)]
]


counter = sum(map(lambda l: Counter(dict(l)), lists), Counter())

print(counter.most_common(3))

Output:

[('a3', 55), ('a2', 50), ('a1', 10)]
>>>

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