如何扫描包含两个元素的子列表的列表并检查相同的元素 [0] 和总结元素 [1] 并创建包含结果的最终列表?

How to scan a list with sublists of two elements and check for same element[0] and the summarize element[1] and create a final list with the result?

我有一个包含两个元素('code' 和长度)的子列表的列表,例如:

list = [['1', 12.0], ['5', 7.4], ['1', 5.0], ['4', 2.3], ['4', 1.0]]

我想扫描列表以查找具有相同 'code' 的子列表元素,然后创建一个总结了长度的最终列表,如下所示:

final_list = [['1', 17.0], ['5', 7.4], ['4', 3.3]]

像这样的字典也可以:final_dict = {'1': 17.0, '5': 7.4, '4': 3.3}

我该怎么做?非常感谢您的帮助!

使用collections.defaultdict

例如:

from collections import defaultdict

lst = [['1', 12.0], ['5', 7.4], ['1', 5.0], ['4', 2.3], ['4', 1.0]]
result = defaultdict(float)
for k, v in lst:
    result[k] += v
print(result)    #for normal dict use print(dict(result))

输出:

defaultdict(<class 'float'>, {'1': 17.0, '5': 7.4, '4': 3.3})

你可以试试:

correlation = {}
sumlist = []
for item in list:
    if item[0] in correlation.keys():
        correlation[item[0]] += item[1]
    else:
        correlation[item[0]] = item[1]

for k, v in correlation.items():
    sumlist.append([k, v])

这不需要模块。 Sumlist 是结果。