2024-10-01 05:02:46 发布
网友
我对编码非常陌生,我想知道是否可以将python中的数组限制为100项。在
如果可能的话,你能继续往这个数组里加,把数组里的旧数推出来吗?因此,每次添加新号码时,都应该将最旧的号码推开以腾出空间。在
提前非常感谢!在
是的,可以通过^{}:
from collections import deque lst = deque([], 100)
与list.append,deque.append工作到位:
list.append
deque.append
如何创建一个简单的函数来实现这一点:
def add_to_array(lst, item, maxsize): if len(lst) >= maxsize: lst.pop(0) lst.append(item)
工作原理如下:
注意:如果您正在寻找更有效的方法,您可以使用^{},正如另一个答案中指出的那样。在
下面是一个使用deque模拟所需行为的示例:
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)
是的,可以通过^{} :
与
^{pr2}$list.append
,deque.append
工作到位:如何创建一个简单的函数来实现这一点:
工作原理如下:
^{pr2}$注意:如果您正在寻找更有效的方法,您可以使用^{} ,正如另一个答案中指出的那样。在
下面是一个使用
deque
模拟所需行为的示例:相关问题 更多 >
编程相关推荐