[英]Average a list of dictionaries based on key
具有n個字典的列表,下面是一個示例:
n = [
{'GB_written': '6.63',
'avg_write_put': '81.45',
'bGB_written': '4.78',
'bbytes_written': '5129101312',
'body_len': '512',
'body_len_dist': '32',
'bytes_written': '7118499840',
'cache_size': '2.00',
'device': 1,
'documents': '1000000',
'duration': '60',
'engine': 2,
'key_len': '32',
'key_len_dist': '2',
'read_ops': '31287.45',
'read_us': '31.96',
'reads': '1879063',
'thread_reader': '1',
'thread_writer': '1',
'total_ops': '2885853',
'write_amp': '9.4',
'write_ops': '16763.61',
'write_us': '59.65',
'writes': '1006790',
'written_perdoc': '4.97'},
# more dictionaries
]
我試圖將它們平均化,然后迭代出每個字典,然后迭代每個具有函數的鍵:
def prepare_data(data):
avg = {
'engine' : 0,
'device' : 0,
'documents' : 0,
'thread_reader': 0,
'thread_writer' : 0,
'cache_size' : 0,
'key_len' : 0,
'key_len_dist' : 0,
'body_len' : 0,
'body_len_dist' : 0,
'duration' : 0,
'reads' : 0,
'read_ops' : 0,
'read_us' : 0,
'writes' : 0,
'write_ops' : 0,
'write_us' : 0,
'total_ops' : 0,
'bytes_written' : 0,
'GB_written' : 0,
'bbytes_written' : 0,
'bGB_written' : 0,
'avg_write_put' : 0,
'written_perdoc' : 0,
'write_amp' : 0
}
for key_dict in data:
for key, val in key_dict.iteritems():
value= float(val)
avg[key] = sum( float(avg[key]) + float(value)) / len(data)
return avg
我看到這樣的錯誤:它無法跨浮點值進行迭代。
TypeError: 'float' object is not iterable
我感到困惑,因為這是如何發生的以及如何解決此問題並使代碼正常工作。
您嘗試在單個 float
值上使用sum()
:
sum( float(avg[key]) + float(value))
那將不起作用,因為sum()
希望您給它一個序列。 您不需要使用sum()
來累加兩個float
值,而+
就足夠了。
您無法像這樣計算平均值; 您需要先對所有值求和,然后再用一個單獨的步驟除以長度:
for key_dict in data:
for key, val in key_dict.iteritems():
avg[key] += float(val)
return {key: value / len(data) for key, value in avg.iteritems()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.