Reputation: 19
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
Upvotes: 0
Views: 374
Reputation: 10809
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)]
>>>
Upvotes: 1