【问题标题】:How can I get the first value of a deque without deleting it?如何在不删除双端队列的情况下获得第一个值?
【发布时间】:2018-03-02 04:45:11
【问题描述】:

我使用 Python 3.6.1,并且经常使用集合中的 deque() ,因为它很方便。这一次,我需要获取双端队列的第一个值,并想知道它是否可能。

问题是我可以使用.popleft() 做到这一点,但它最终会同时删除该值。我想到了list(deque01)[0],但是我担心deque01很大或者获取第一个值的过程会重复很多次时是否消耗资源。有什么方法或技巧可以有效地做到这一点?

【问题讨论】:

    标签: python deque


    【解决方案1】:

    对于deque 数据结构,这通常称为“peek”操作,而在 Python 中它只是使用通常的数据模型的__getitem__ dunder 实现的。

    下面这个例子直接取自docs:

    >>> from collections import deque
    >>> d = deque('ghi')                 # make a new deque with three items
    >>> d[0]                             # peek at leftmost item
    'g'
    >>> d[-1]                            # peek at rightmost item
    'i'
    

    请注意,尽管界面看起来类似于列表,但双端队列仅提供对最左侧或最右侧项目的快速访问。访问中间数据的速度较慢,而不是列表,在任何地方都可以快速索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2020-01-07
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      相关资源
      最近更新 更多