连续替换数组或列表中的值

2024-10-01 05:02:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码非常陌生,我想知道是否可以将python中的数组限制为100项。在

如果可能的话,你能继续往这个数组里加,把数组里的旧数推出来吗?因此,每次添加新号码时,都应该将最旧的号码推开以腾出空间。在

提前非常感谢!在


Tags: 编码空间数组号码陌生旧数
2条回答

是的,可以通过^{}

from collections import deque

lst = deque([], 100)

list.appenddeque.append工作到位:

^{pr2}$

如何创建一个简单的函数来实现这一点:

def add_to_array(lst, item, maxsize):

    if len(lst) >= maxsize:
        lst.pop(0)

    lst.append(item)

工作原理如下:

^{pr2}$

注意:如果您正在寻找更有效的方法,您可以使用^{},正如另一个答案中指出的那样。在

下面是一个使用deque模拟所需行为的示例:

>>> lst = deque((i for i in range(1, 10)), maxlen=10)
>>> lst
deque([1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
>>> lst.append(10)
>>> lst
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxlen=10)
>>> lst.append(11)
>>> lst
deque([2, 3, 4, 5, 6, 7, 8, 9, 10, 11], maxlen=10)

相关问题 更多 >