首页 > 解决方案 > 如何在python中的字典列表中按值分组?

问题描述

[{'A': '1', 'P': '3253'},{'A': '2', 'P': '3127'},{'A': '1', 'P': '3056'}]

打印 A 值的唯一数量对于每个唯一的 A 值,平均P(按 A 值分组)输出应该是:

[('A':'1', 'P':'3154.5'},{'A': '2', 'P': '3127'}]

标签: python-3.xlistpython-2.7dictionary

解决方案


首先收集所有相似的键来计算平均值:

LoD=[{'A': '1', 'P': '3253'},{'A': '2', 'P': '3127'},{'A': '1', 'P': '3056'}]

out={}
for d in LoD:
    k=('A', d['A'])
    out.setdefault(k, []).append(float(d['P']))

然后重新格式化为具有平均值的字典列表:

newLoD=[{t[0]:t[1], 'P':str(sum(sl)/len(sl))} for t,sl in out.items()]  

>>> newLoD
[{'A': '1', 'P': '3154.5'}, {'A': '2', 'P': '3127.0'}] 

推荐阅读