添加元组列表并对其进行排序

时间:2016-12-18 16:20:04

标签: python list sum

我有以下元组列表:

mylist=[('a', 3), ('b', 2), ('c', 8)]
mylist2=[('a', 3), ('b', 5), ('c', 20), ('d', 5)]

有没有办法可以将所有具有相同名称的值相加并在Python中对它们进行排序?类似的东西:

[('c', 28), ('b', 7), ('a', 6), ('d', 5)]

1 个答案:

答案 0 :(得分:1)

如果我是你,我会这样做:

>>> mylist=[('a', 3), ('b', 2), ('c', 8)]
>>> mylist2=[('a', 3), ('b', 5), ('c', 20), ('d', 5)]

# Step 1: Convert the list of tuples to `dict`
>>> dict_1, dict_2 = dict(mylist), dict(mylist2)

# Step 2: get set of all keys
>>> all_keys = set(dict_1.keys() + dict_2.keys())

# Step 3: Get `sum` of value for each key
>>> sum_list = [(k, dict_1.get(k, 0) + dict_2.get(k, 0)) for k in all_keys]

然后将列表排序为:

>>> from operator import itemgetter

# Step 4: Sort in descending order based on value at index 1
>>> sorted(sum_list, key=itemgetter(1), reverse=True)
[('c', 28), ('b', 7), ('a', 6), ('d', 5)]

注意:它假定两个列表的元组中第0个索引处的是唯一的。