Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从有序dict计算平均值_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 从有序dict计算平均值

Python 从有序dict计算平均值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一个有序列表,其项是一对值,格式如下。我想计算每个唯一秒的平均毫秒(右值)时间(左值) 有没有一个简单的方法可以做到这一点 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 您的dict似乎不正确,因为您有多个具有相同密钥的条目。但无论如何,假设您有一个格式正确的O

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

有没有一个简单的方法可以做到这一点

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

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

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

猜测示例的结果应该是{'20170822-13:56:02':50.0,'20170822-13:56:03':50.5}的答案,这里有一个解决方案:

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)

您提供的数据不是一条命令,也不是一行:
sum([i for i in x.values())/len(list(x.values())
avg=np.average(list(x.values())
如果他已经有了命令,那么它就是一行了……这是真的,而且可能更可读。如果有什么问题的话,我的解决方案只依赖于std库,可能需要也可能不需要。使用std库不是问题:)