[英]Iterate over deque in python
Since a deque is a doubly linked list, I should be able to iterate through it in order without any performance cost compared to a list.由于双端队列是双向链表,因此与列表相比,我应该能够按顺序遍历它而不会产生任何性能成本。 However, the following will be much slower than iterating through a list
然而,下面会比迭代慢得多通过名单
for i in range(0, len(d)):
doSomethingWith(d[i])
Since each time it goes to d[i]
starting at d[0]
.因为每次它都从
d[0]
开始到d[i]
d[0]
。 How do I make it iterate properly?我如何使它正确迭代?
You can directly iterate over the deque.您可以直接迭代双端队列。
for i in d:
doSomethingWith(i)
(see the examples in the documentation: https://docs.python.org/2/library/collections.html#collections.deque ) (请参阅文档中的示例: https : //docs.python.org/2/library/collections.html#collections.deque )
I used a while
loop for deque
iteration, as follows:我使用了一个
while
循环进行deque
迭代,如下:
from collections import deque
lst = [1,2,4,8]
queue=deque(lst)
print(queue)
while queue:
print('{}{}'.format("head: ",queue[0]))
queue.popleft()
output:输出:
deque([1, 2, 4, 8])
head: 1
head: 2
head: 4
head: 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.