Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.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_Python_Deque - Fatal编程技术网

循环缓冲区python

循环缓冲区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

我想使用循环缓冲区(即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 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