0

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

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

2 回答 2

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()]
于 2012-10-24T15:35:04.173 回答
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}]
于 2012-10-24T15:41:39.383 回答