python-3.x - 如何在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'}]
解决方案
首先收集所有相似的键来计算平均值:
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'}]
推荐阅读
- reactjs - 如何切换以显示和隐藏 Reactjs 中的元素?
- jquery - Django中的喜欢按钮
- python - 是否有 python 函数来查找浮点数是否属于特定范围?
- django - 我该如何解决这个错误“类型对象'用户'没有属性'对象'”
- python - 正则表达式 - 计算一个单词在文本中出现的次数
- python - 正则表达式:如何摆脱字符串中的 \n?
- html - 元视口打破责任(使一切变得非常小)
- css - CSS 适用于 chrome 开发工具和实时 CSS 编辑器,但不适用于 wordpress 实时站点
- javascript - 测量单页应用程序中的页面加载时间速度
- python - 谁能一步一步解释这个过程