我想创建一个高效的circular buffer在 python 中(目的是取缓冲区中整数值的平均值)。
这是使用列表收集值的有效方法吗?
def add_to_buffer( self, num ):
self.mylist.pop( 0 )
self.mylist.append( num )
什么会更有效(为什么)?
最佳答案
我会使用 collections.deque
带有 maxlen
参数
>>> import collections
>>> d = collections.deque(maxlen=10)
>>> d
deque([], maxlen=10)
>>> for i in xrange(20):
... d.append(i)
...
>>> d
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], maxlen=10)
有一个recipe在 deque
的文档中与您想要的类似。我断言它是最有效的完全取决于这样一个事实,即它是由一个非常熟练的团队用 C 实现的,他们习惯于编写一流的代码。
关于python - 有效的循环缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4151320/