【问题标题】:How to do group by values in list of dictionary in python?如何在python中的字典列表中按值分组?
【发布时间】:2021-10-17 13:21:03
【问题描述】:

[{'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.x list python-2.7 dictionary


【解决方案1】:

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

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'}] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多