【发布时间】:2021-12-14 18:42:56
【问题描述】:
有没有办法让列表的长度保持不变,同时在迭代过程中不断地追加它?
我尝试了双端队列,但它给了我一个运行时错误,我读到它不可能 leftpop 元素。
我用 list.pop(0) 和 list.append() 尝试过,但索引搞砸了。
双端队列方法将是完美的,指定一个最大长度,然后只有一个“滚动窗口”,如果需要稍后重做,将在其中添加 slice_items,并且开头的项目会弹出以不会耗尽内存。基本上它可以永远运行,直到工作完成,没有新元素被添加回来,列表被耗尽
for symbol in symbols:
slices = ['year1month1', 'year1month2', 'year1month3', 'year1month4']
for slice_item in slices:
# do something here
if something didnt work:
slices.pop(0)
slices.append(slice)
...
这是我的运行时错误方法:
for symbol in symbols:
slices = deque(['year1month1', 'year1month2', 'year1month3', 'year1month4'],maxlen=24)
for slice_item in slices:
# do something here
if something didnt work:
slices.append(slice)
...
更新,感谢@Buran;为了完整性:
from collections import deque
symbols = ('a','b','...','n')
slices = ('year1month1', 'year1month2', 'year1month3')
for symbol in symbols:
slice_queue = deque(range(len(slices)))
while slice_queue:
slice_idx = slice_queue[0]
# do something
done = symbols + slices[slice_idx]
if done:
slice_queue.popleft()
else:
slice_queue.rotate(-1)
【问题讨论】:
-
您在问题中提到的
deque有什么问题?看collections.deque -
根据geeksforgeeks.org/deque-in-python,您可以在
deques 上使用popleft() -
@Einliterflasche,不需要,他们可以设置
maxlen -
问题是,当我在 deque 上离开时,我得到: RuntimeError: deque mutated during iteration
-
值得一提的是,您在迭代列表时不应更改列表。看看stackoverflow.com/questions/1207406/…
标签: python foreach collections deque