在Python中平均数组中相同类型的分数

时间:2012-10-24 15:29:13

标签: python arrays average

假设我有一个如下所示的示例数组:

color_values = [{'score': 3, 'color': u'blue'}, {'score': 1, 'color': u'red'}, {'score': 4, 'color': u'green'}, {'score': 4, 'color': u'red'}, {'score': 2, 'color': u'blue'}]

如何在python中编写一个代码,用于平均所有相同颜色得分的新数组?所以新数组看起来像:

color_values = [{'score': 2.5, 'color': u'blue'}, {'score': 2.5, 'color': u'red'}, {'score': 4, 'color': u'green'}]

2 个答案:

答案 0 :(得分:1)

解决此类问题的最简单(如果不是最短)方法是从密钥到值列表构建dict,然后聚合它:

by_color = {}
for obj in color_values:
    by_color.setdefault(obj['color'], []).append(obj['score'])
color_values = [{'score': float(sum(value)) / len(value), 'color': key}
                for key, value in by_color.items()]

答案 1 :(得分:1)

使用列表理解:

average = lambda l: sum(l) / float(len(l))
[{'score': average([d['score'] for d in color_values if d['color'] is color]),
  'color': color} for color in set(d['color'] for d in color_values)]

输出:

>>> color_values = [{'score': 3, 'color': u'blue'}, {'score': 1, 'color': u'red'}, {'score': 4, 'color': u'green'}, {'score': 4, 'color': u'red'}, {'score': 2, 'color': u'blue'}]
>>> average = lambda l: sum(l) / float(len(l))
>>> [{'score': average([d['score'] for d in color_values if d['color'] is color]),
...   'color': color} for color in set(d['color'] for d in color_values)]
[{'color': u'blue', 'score': 2.5}, {'color': u'green', 'score': 4.0}, {'color': u'red', 'score': 2.5}]