减少字典列表的优雅方法? [英] elegant way to reduce a list of dictionaries?
问题描述
我有一个词典列表,每个词典包含完全相同的键。我想找到每个键的平均值,我想知道如何使用reduce进行操作(或者,如果不可能,使用比嵌套 for
s更为优雅的方法) )。
I have a list of dictionaries and each dictionary contains exactly the same keys. I want to find the average value for each key and I would like to know how to do it using reduce (or if not possible with another more elegant way than using nested for
s).
以下是列表:
[
{
"accuracy": 0.78,
"f_measure": 0.8169374016795885,
"precision": 0.8192088044235794,
"recall": 0.8172222222222223
},
{
"accuracy": 0.77,
"f_measure": 0.8159133315763016,
"precision": 0.8174754717495807,
"recall": 0.8161111111111111
},
{
"accuracy": 0.82,
"f_measure": 0.8226353934130455,
"precision": 0.8238175920455686,
"recall": 0.8227777777777778
}, ...
]
我想找回我这样的字典:
I would like to get back I dictionary like this:
{
"accuracy": 0.81,
"f_measure": 0.83,
"precision": 0.84,
"recall": 0.83
}
这是我到目前为止的内容,但我不喜欢它:
Here is what I had so far, but I don't like it:
folds = [ ... ]
keys = folds[0].keys()
results = dict.fromkeys(keys, 0)
for fold in folds:
for k in keys:
results[k] += fold[k] / len(folds)
print(results)
推荐答案
作为替代方案,如果要对数据进行此类计算,那么您不妨使用 pandas (这对于一次过来说是过大的,但是会大大简化此类任务...)
As an alternative, if you're going to be doing such calculations on data, then you may wish to use pandas (which will be overkill for a one off, but will greatly simplify such tasks...)
import pandas as pd
data = [
{
"accuracy": 0.78,
"f_measure": 0.8169374016795885,
"precision": 0.8192088044235794,
"recall": 0.8172222222222223
},
{
"accuracy": 0.77,
"f_measure": 0.8159133315763016,
"precision": 0.8174754717495807,
"recall": 0.8161111111111111
},
{
"accuracy": 0.82,
"f_measure": 0.8226353934130455,
"precision": 0.8238175920455686,
"recall": 0.8227777777777778
}, # ...
]
result = pd.DataFrame.from_records(data).mean().to_dict()
哪一个给您:
{'accuracy': 0.79000000000000004,
'f_measure': 0.8184953755563118,
'precision': 0.82016728940624295,
'recall': 0.81870370370370382}
这篇关于减少字典列表的优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!