如何在 'for each' 迭代期间附加到列表的同时保持列表的长度不变

How to keep the length of a list constant while appending to it during 'for each' iteration

有没有办法在迭代期间不断追加列表的同时保持列表的长度不变?

我试过双端队列,但它给了我一个 运行时间错误,我读到它不可能 leftpop 元素。

我用 list.pop(0) 和 list.append() 试过了,但索引搞砸了。

deque method 将是完美的,指定一个最大长度,然后只需要一个 'rolling window',其中 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)

编辑:再次阅读你的问题后,我想我理解错了,但无论如何我会保留我原来的答案,见最后。

看看collections.deque。我认为您需要旋转双端队列,而不是 maxlen。这样你就创建了一个队列,最后发送失败的任务。

from collections import deque
from random import choice

success = [True, False]

deq = deque(range(5))
while deq:
    if choice(success): # for the example randomly choose result of operation
        num = deq.popleft()
        print(f'Success: {num}')
    else:
        print(f'Fail: {deq[0]}')
        deq.rotate(-1) # rotate the deque to left
        print(deq)

示例输出:

Fail: 0
deque([1, 2, 3, 4, 0])
Fail: 1
deque([2, 3, 4, 0, 1])
Fail: 2
deque([3, 4, 0, 1, 2])
Fail: 3
deque([4, 0, 1, 2, 3])
Success: 4
Fail: 0
deque([1, 2, 3, 0])
Success: 1
Success: 2
Fail: 3
deque([0, 3])
Fail: 0
deque([3, 0])
Success: 3
Success: 0

我原来的回答:

查看 collections.deque 并设置 maxlen

来自文档:

If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

例子

from collections import deque

deq = deque(maxlen=3)

for num in range(10):
    deq.append(num)

print(deq)

输出

deque([7, 8, 9], maxlen=3)