Python - 使用 popleft() 遍历双端队列

Python - Iterating through a deque with popleft()

我一直在寻找迭代双端队列的最佳方法,同时使用 popleft 使用第一个元素并减少每次迭代的队列。我基本上想在双端队列中删除第一个,运行 一些代码使用这个值,然后执行相同的过程,直到双端队列中没有更多的值。

我在网上找到的最好的方法是使用 try and catch 块来捕获 IndexError:

try: 
    while mydeque: 
        value = mydeque.popleft()
except IndexError: 
# handle empty mydeque

抛出异常当然不是最好的方法。我也会捕获 while 循环中发生的任何 IndexError,这并不理想。使用 for 循环不起作用,因为我会在迭代期间修改双端队列。

最好的方法是什么?

mydeque为空时,在while循环中解析为False

while mydeque:
    value = mydeque.popleft()

这将 运行 通过 mydeque 中的所有值。

您可以将 try/except 放在 while 循环中;这样你就可以确保它只捕获由 popleft

抛出的 IndexError

https://pymotw.com/2/collections/deque.html

while True:
  try:
    print d.popleft()
  except IndexError:
    break

您可以按照@slightlynybbled 的建议使用while mydeque:... 或者 while 0 < len(mydeque):...什么基本一样

while 0 < len(mydeque):
    value = mydeque.popleft()