从有序字典计算平均值

时间:2017-08-22 01:59:31

标签: python python-3.x dictionary

我有一个有序列表,其项目是以下格式的一对值。我想计算每个唯一秒的平均毫秒(右值)时间(左值)

有一种简单的方法吗?

TestCase

2 个答案:

答案 0 :(得分:0)

猜测你的例子的结果应该是 {'20170822-13:56:02':50.0,'20170822-13:56:03':50.5} 这里是一个解决方案:< / p>

raw_input = [
    '20170822-13:56:02 :  50 ms',
    '20170822-13:56:03 :  36 ms',
    '20170822-13:56:03 :  59 ms',
    '20170822-13:56:03 :  40 ms',
    '20170822-13:56:03 :  67 ms'
]

result_dict = {}

for raw_input_item in raw_input:
    # Transform inpu item in a two item list alo [second, millisecond]. e.g. ['20170822-13:56:03', '67'].
    key_value = raw_input_item.rstrip('ms').split(' :  ')
    # Accumulate the total milliseconds and the count entries for each second, so we can calculate average at the end.
    value = result_dict.get(key_value[0], False)
    if value:
        # The key exist, just add one to the entries counter and the milliseconds to the total milliseconds to that key (second)
        value[0] += 1
        value[1] += int(key_value[1])
    else:
        # The key do not exist, just initialize the value with entry counter 1 and the total milliseconds
        # the this first key appearance bring with it.
        result_dict[key_value[0]] = [1, int(key_value[1])]

for key in result_dict:
    result_dict[key] = result_dict[key][1]/result_dict[key][0]

print(result_dict)

答案 1 :(得分:-1)

您的dict似乎不正确,因为您有多个具有相同键的条目。但无论如何,假设你有一个格式正确的OrderedDict(就像我在下面生成的那样),你可以得到平均值:

from collections import OrderedDict
import numpy as np
x = OrderedDict()
x['a'] = 1 
x['b'] = 2 
x['c'] = 3 
avg = np.average(list(x.values()))

返回2.0作为avg

的答案