将python列表转换为字典并添加具有相同键的值

时间:2017-08-18 05:27:53

标签: python list dictionary

new Refresh().execute();
  

如何将datalist转换为字典,分配键[868,869]并在内部列表的索引2和3处添加具有相似键值的值,即332.31,144.00和19.94,8.64

datalist = [[868, 'S00086', 640.80, 38.45], [869, 'S00087', 332.31, 19.94], [869, 'S00087', 144.00, 8.64],]

请建议有效的解决方案,提前致谢

2 个答案:

答案 0 :(得分:4)

您可以使用itertools.groupby(),对每个子列表的第一项进行分组:

from itertools import groupby

datalist = [[868, 'S00086', 640.80, 38.45], [869, 'S00087', 332.31, 19.94], [869, 'S00087', 144.00, 8.64],]
datadict = {}

for k, group in groupby(sorted(datalist), key=lambda x: x[0]):
    for v in group:
        if k not in datadict:
            datadict[k] = v[1:]
        else:
            datadict[k][1] += v[2]
            datadict[k][2] += v[3]
print(datadict)  # {868: ['S00086', 640.8, 38.45], 869: ['S00087', 476.31, 28.580000000000002]}

答案 1 :(得分:1)

使用[1, 5, 9, 3] itertools.groupby()函数的解决方案:

sum()

输出:

import itertools
datalist = [[868, 'S00086', 640.80, 38.45], [869, 'S00087', 332.31, 19.94], [869, 'S00087', 144.00, 8.64]]

result = {}
# grouping inner lists by the 1st item value
for k,g in itertools.groupby(sorted(datalist), key=lambda x: x[0]):
    g = list(g)
    # summing up values for grouped items
    result[k] = g[0][1:] if len(g) == 1 else [g[0][1], sum(i[2] for i in g), sum(i[3] for i in g)]

print(result)