返回字典列表中特定键的平均值/平均值

spi*_*paz 0 python iteration dictionary iterator python-3.x

这可能是重复的,所以如果我没找到,请告诉我.

我的问题在标题中.

我知道下面的代码会这样做,但我不认为这是应该怎么做的.这可以压缩到一个更干净的功能,做同样的事情吗?内置函数怎么样?

def find_sorted_avg(dict_list, key):
    total = 0

    for item in dict_list:
        total += item[key]

    return total / len(dict_list)
Run Code Online (Sandbox Code Playgroud)

如果您知道更好的方法,请告诉我.

Jea*_*bre 5

你想要key在你的词典列表中加总a的所有值.

您可以将生成器理解提供给sum,并除以列表的长度,在一行中:

total = sum(item.get(key,0) for item in dict_list) / len(dict_list)
Run Code Online (Sandbox Code Playgroud)

get(key,0) 确保如果一个字典中没有键,它仍然可以工作(当键不在字典中时发出0)

(当然,如果你想这样大声崩溃,而不是取代item.get(key,0)item[key])