简体   繁体   English

词典列表中键值的平均值

[英]Average of key values in a list of dictionaries

I have this list of dictionaries : 我有这个字典清单:

[{'Eva': [4, 8, 2]}, {'Ana': [57, 45, 57]}, {'Ada': [12]}]

I need to get the average of each key value, so that the output is : 我需要获取每个键值的平均值,以便输出为:

[{'Eva': [5], {'Ana' : [53]}, {'Ada':[12]}]

The average must be rounded up or down by adding 0.5 and taking the only the integer part. 平均值必须通过加0.5并仅取整数部分而四舍五入。 For example, if the average is 4.3 adding 0.5 equals 4.8, so the output is 4. If the average is 4.6 adding 0.5 equals 5.1, so the output is 5. 例如,如果平均值为4.3加0.5等于4.8,则输出为4。如果平均值为4.6加0.5等于5.1,则输出为5。

I know how to use iteritems() to iterate over a dictionary, but since this is a list I don't know how to reach every value. 我知道如何使用iteritems()遍历字典,但是由于这是一个列表,所以我不知道如何达到每个值。

Thanks in advance. 提前致谢。

Define an average function and then use a nested list / dict comprehension to get the averages for each key for each dictionary in the list. 定义一个average函数,然后使用嵌套的list / dict获取列表中每个词典的每个键的平均值。

>>> from __future__ import division
>>> lst = [{'Eva': [4, 8, 2]}, {'Ana': [57, 45, 57]}, {'Ada': [12]}]
>>> avg = lambda x: int(round(sum(x) / len(x)))
>>> [{k: avg(v) for k, v in d.items()} for d in lst]
[{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]

If you want the average to be wrapped in a list, just use [avg(v)] : 如果您希望将平均值包含在列表中,请使用[avg(v)]

>>> [{k: [avg(v)] for k, v in d.items()} for d in lst]
[{'Eva': [5]}, {'Ana': [53]}, {'Ada': [12]}]

You can use zip and numpy functions mean and round for this task: 您可以使用zipnumpy函数的meanround功能完成此任务:

In [8]: import numpy as np

In [9]:  [dict(zip(d.keys(), [int(np.round(np.mean(d.values())))])) for d in L]

#Out[9]: [{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]

Version with "less" parenthesis: 带“较少”括号的版本:

[dict(zip(d.keys(), [np.array(d.values()).mean().round().astype(int)])) for d in L]

This is an "easy to read and understand" solution. 这是一个“易于阅读和理解”的解决方案。 I guess from your question that you do not have too much confidence with python so, I will keep it very basic. 我想从您的问题中可以看出,您对python不太有信心,因此,我将使其保持非常基础。

myList = [{'Eva': [4, 8, 2]}, {'Ana': [57, 45, 57]}, {'Ada': [12]}]

result = []
for item in myList:
    for k,v in item.items(): #use iteritems() if Python2
        average = round(sum(v)/len(v)) #round to the closest integer
        result.append({k:average})

>>>print(result)
[{'Eva': 5}, {'Ana': 53}, {'Ada': 12}]

You can do: 你可以做:

data = [{'Eva': [4, 8, 2]}, {'Ana': [57, 45, 57]}, {'Ada': [12]}]
outdata = []

for item in data:
    tmp = {}
    for key, val in item.iteritems():
        avg = reduce(lambda x, y: x + y, val) / len(val)
        tmp[key] = [avg]
    outdata.append(tmp)

Which will also work in the case where you have dictionaries with multiple keys (although the additional variable is probably wasteful if that can never happen). 在具有多个键的字典的情况下,这也将起作用(尽管如果永远不会发生附加变量,则可能很浪费)。

Oneliner: Oneliner:

In: 在:

[{el.keys()[0]: [int( round(1.0 * sum(el.values()[0]) / len(el.values()[0]) ))]} for el in li]

Out: 出:

[{'Eva': [5]}, {'Ana': [53]}, {'Ada': [12]}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM