How do I implement a circular buffer in Python?

痞子三分冷 提交于 2020-01-11 10:48:12

问题


I have a matrix for instance

a=[12,2,4,67,8,9,23]

and I would like a code that appends a value say 45 to it and removes the first value '12' so in essence I want to make

a = [2,4,67,8,9,23,45]

I want to work with regular matrices not numpy matrices so I can't use hstack or vstack How do I do this in python? Any help would be appreciated, thanks


回答1:


The simplest way:

a = a[1:] + [45]



回答2:


Use a deque.

http://docs.python.org/2/library/collections.html#collections.deque

>>> import collections
>>> d = collections.deque(maxlen=7)
>>> d.extend([12,2,4,67,8,9,23])
>>> d.append(45)
>>> print d
deque([2, 4, 67, 8, 9, 23, 45], maxlen=7)



回答3:


You can do this:

a=[12,2,4,67,8,9,23]
a.append(45)
a.pop(0)


来源:https://stackoverflow.com/questions/13628710/how-do-i-implement-a-circular-buffer-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!