循环缓冲区python
我想使用循环缓冲区(即x作为deque)来实现这一点 我知道如何实现一个简单的循环缓冲区:循环缓冲区python,python,deque,Python,Deque,我想使用循环缓冲区(即x作为deque)来实现这一点 我知道如何实现一个简单的循环缓冲区: from collections import deque import time d = deque(maxlen=4) bool = True i = 1 y = 0 while bool: d.append(i) i = i + 1 print(d) time.sleep(1) 但是我不能用它来复制第一个代码。这样做有效吗 from collections im
from collections import deque
import time
d = deque(maxlen=4)
bool = True
i = 1
y = 0
while bool:
d.append(i)
i = i + 1
print(d)
time.sleep(1)
但是我不能用它来复制第一个代码。这样做有效吗
from collections import deque
container = deque(maxlen=4)
while True:
accel_data = sensor.get_accel()
curr_date = datetime.utcnow().strftime('%Y-%m-%d')
curr_time = datetime.utcnow().strftime('%H:%M:%S.%f')
entry = accel_data + (curr_date, curr_time)
container.append(entry)
print(container) # this is not strictly necessary
以下是一些提示:
为什么你不能复制它?“不要声明你不打算使用的变量。”:我忘了在“i=i+1”之前添加几行:对于范围(4)中的y:print x[i][y],但是在引入代码时要小心,因为你的代码中的
x
变成了容器,其最大长度是固定的(4
在示例中),因此如果您继续添加它,i
将超出范围。嗯,我无法尝试您的代码,因为我需要我的树莓,但我认为这是一个误解,无论如何,我将更好地解释我的第一个代码问题我有一个数组(“x”),并在每一步中添加所有这些信息。因此,在4个步骤之后,例如:0.48,0.89,1.216/12/1720.45.34=>x[0]------------0.48,0.90,1.416/12/1720.45.35=>x[1]------------0.48,0.91,1.216/12/1720.45.36=>x[2]--0.48,0.94,1.216/12/1720.45.37=>x=>[3] 因此,“maxlen”不是指“j”(x[i]中的元素,始终为5),而是指“i”,如果您使用container=deque(maxlen=4)
更改container=[]
,则此代码也可以工作(理想情况下)最初有。列表
版本将允许容器
在每次迭代中增长1,因此如果您可以访问容器
,索引不断增长,如container[i]
(假设您在循环内的某个地方有i+=1
或类似的内容,并且在循环外初始化了i=0
)。另一方面,如果容器
现在是deque
,当i
大于其最大大小时访问它,将导致容器[i]
超出i
的某些值的范围,而不管条目
中有什么。
from collections import deque
container = deque(maxlen=4)
while True:
accel_data = sensor.get_accel()
curr_date = datetime.utcnow().strftime('%Y-%m-%d')
curr_time = datetime.utcnow().strftime('%H:%M:%S.%f')
entry = accel_data + (curr_date, curr_time)
container.append(entry)
print(container) # this is not strictly necessary