Python双端队列的标准差

4

我正在使用Python deque数据类型计算简单移动平均值,我想知道是否有一种方法可以将它视为某种数组,并找到deque的标准差?


1
能否提供一个具体的例子,这将有助于更好地理解您的需求。您可以对deque应用list()函数,以获得相同顺序和值的普通列表。这样是否足够?或者您还需要计算标准差的代码等其他内容? - Tim Peters
1
你可以遍历双向队列并获取其长度。还需要什么? - user395760
谢谢,我不知道那么清楚,最终我做了类似于dlist[n]的事情,并对其进行迭代。 - eWizardII
1个回答

5

是的,你可以将 deque 视为数组。它既可迭代又可索引 :-)

以下是使用宽度为五的滑动窗口计算移动平均值和移动标准差的示例:

>>> from random import randrange
>>> from collections import deque
>>> from statistics import mean, stdev

>>> window = deque((randrange(100) for i in range(5)), 5)
>>> print(mean(window), stdev(window))
55.4 30.104816890325043
>>> for i in range(10):
        x = randrange(100)
        window.append(x)
        print(mean(window), stdev(window))

49.4 26.782456944798774
42.8 28.74369496080836
53 19.557607215607945
44.6 15.208550226763892
44.2 14.75466028073842
37.4 18.716303053755034
47.4 22.142718893577637
36.2 29.609120216581918
29.2 33.80384593504118
30 34.66266002487403

对于较大的窗口,通过保留运行总数可以更有效地计算移动平均值和标准偏差。请参见 John Cook 的这篇博客文章。 使用双向队列(deque)可以轻松更新运行总数,快速访问正在被移除的元素和正在添加的元素。

>>> window = deque((randrange(100) for i in range(5)), 5)
>>> for i in range(10):
        print(window, end='\t')
        old = window[0]
        new = randrange(100)
        window.append(new)
        print(f'Out with the {old}. In with the {new}')

deque([8, 53, 59, 86, 34], maxlen=5)    Out with the 8. In with the 58
deque([53, 59, 86, 34, 58], maxlen=5)   Out with the 53. In with the 81
deque([59, 86, 34, 58, 81], maxlen=5)   Out with the 59. In with the 31
deque([86, 34, 58, 81, 31], maxlen=5)   Out with the 86. In with the 21
deque([34, 58, 81, 31, 21], maxlen=5)   Out with the 34. In with the 11
deque([58, 81, 31, 21, 11], maxlen=5)   Out with the 58. In with the 91
deque([81, 31, 21, 11, 91], maxlen=5)   Out with the 81. In with the 42
deque([31, 21, 11, 91, 42], maxlen=5)   Out with the 31. In with the 97
deque([21, 11, 91, 42, 97], maxlen=5)   Out with the 21. In with the 94
deque([11, 91, 42, 97, 94], maxlen=5)   Out with the 11. In with the 29

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接