在 Python 中推送和弹出列表的最有效方法是什么?

D.J*_*dan 2 python performance list shift

在 Python 中,如何编写代码将列表的最后一个元素移出并在开头添加一个新元素 - 以在执行时尽可能快地运行?

有一些很好的解决方案涉及使用附加、旋转等,但并非所有解决方案都可以转化为快速执行。

Blc*_*ght 9

不要使用列表。

列表只能在其末尾快速插入和删除项目。你会使用pop(-1)and append,你最终会得到一个堆栈。

相反,请使用collections.deque,它旨在在两端进行有效的添加和删除。在双端队列的“前端”上工作使用popleft和appendleft方法。请注意,“deque”的意思是“双端队列”,发音为“deck”。


Ees*_*aan 8

L = [1, 2, 3]
L.pop() # returns 3, L is now [1, 2]
L.append(4) # returns None, L is now [1, 2, 4]
L.insert(0, 5) # returns None, L is now [5, 1, 2, 4]
L.remove(2) # return None, L is now [5, 1, 4]
del(L[0]) # return None, L is now [1, 4]
L.pop(0) # return 1, L is now [4]
Run Code Online (Sandbox Code Playgroud)


Alo*_*hor 0

您可以使用Python列表对象的插入方法。

l = [1, 2, 3]
#lets insert 10 at biggining, which means at index 0
l.insert(0, 10)
print(l) # this will print [10, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)