Python对象数组 arr=[{'red':{'weight':50},{'blue':{'weight':60},{'red':{'weight':70}]

Python对象数组 arr=[{'red':{'weight':50},{'blue':{'weight':60},{'red':{'weight':70}],python,arrays,list,dictionary,Python,Arrays,List,Dictionary,假设我们想用以下预期输出总结此数组: output=[{'color':'red','count':2,'total':120,'min':50,'max':70,'mean':60}, {'color':'blue','count':1,'total':60,'min':60,'max':60,'mean':60}] 或者: output={'red':{'count':2,'total':120,'min':50,'max':70,'mean':60}, 'blue':{'count':1

假设我们想用以下预期输出总结此数组:

output=[{'color':'red','count':2,'total':120,'min':50,'max':70,'mean':60},
{'color':'blue','count':1,'total':60,'min':60,'max':60,'mean':60}]
或者:

output={'red':{'count':2,'total':120,'min':50,'max':70,'mean':60},
'blue':{'count':1,'total':60,'min':60,'max':60,'mean':60}
我所尝试的:

>{list(i.items())[0][0]:[list(j.items())[0][0]用于arr中的j]。计数(list(i.items())[0][0])用于arr中的i}
{“红色”:2,“蓝色”:1}
>>[{list(i.items())[0][0]:{'count':[list(j.items())[0][0]用于arr中的j]。count(list(i.items())[0][0])用于arr中的i}]
[{'red':{'count':2},'blue':{'count':1}]
>[{'color':列表(i.items())[0][0],'count':[list(j.items())[0][0]用于arr中的j]。计数(列表(i.items())[0][0])用于arr中的i]
[{'color':'red','count':2},{'color':'blue','count':1},{'color':'red','count':2}]

只需收集
'weight'
值的列表,并对其进行总结:

从集合导入defaultdict
进口统计
def汇总(重量):
返回{'count':len(权重),'total':sum(权重),'min':min(权重),'max':max(权重),'mean':statistics.mean(权重)}
arr=[{'red':{'weight':50},{'blue':{'weight':60},{'red':{'weight':70}]
输出=默认DICT(列表)
对于arr中的d:
对于d中的k:
输出[k]。追加(d[k]['weight'])
output={k:总结output.items()中(k,权重)的(权重)}
打印(输出)
输出:

{'red': {'count': 2, 'total': 120, 'min': 50, 'max': 70, 'mean': 60}, 
'blue': {'count': 1, 'total': 60, 'min': 60, 'max': 60, 'mean': 60}}

您可以使用
itertools.groupby
按颜色对列表进行分组(只需先对列表进行排序)(我能想到的最好/最简单的方法是只使用dicts上的tuple),然后循环生成列表<代码>统计。平均值也是获取一组数字平均值的简单方法:

from itertools import groupby
from statistics import mean

arr = [{'red': {'weight': 50}}, {'blue': {'weight': 60}}, {'red': {'weight': 70}}]

output = []
for (k, *_), g in groupby(sorted(arr, key=tuple), key=tuple):
    all_vals = [d[k]['weight'] for d in g]
    output.append({'color': k, 'count': len(all_vals), 'total': sum(all_vals), 'min': min(all_vals), 'max': max(all_vals), 'mean': mean(all_vals)})

这没有任何意义——您的数据摘要包含的信息比它要摘要的数据更多。有可能重申你的问题吗?您可能会发现不使用一行程序而编写一些循环更容易。
[{'color': 'blue', 'count': 1, 'total': 60, 'min': 60, 'max': 60, 'mean': 60},
 {'color': 'red', 'count': 2, 'total': 120, 'min': 50, 'max': 70, 'mean': 60}]