Python 中的双端队列是如何实现的,它们什么时候比列表更糟糕?
我最近开始研究如何在 Python 中实现各种数据结构,以便使我的代码更加高效。在研究列表和双端队列如何工作时,我发现当我想要移动和取消移动时,我可以获得好处,将列表中的 O(n) 时间减少到双端队列中的 O(1) (列表被实现为固定长度数组,这些数组具有每次在前面插入某些内容时都会完全复制,等等...)。我似乎找不到双端队列如何实现的细节,以及它与列表相比的缺点的细节。有人可以帮我解答这两个问题吗?
I've recently gotten into investigating how various data structures are implemented in Python in order to make my code more efficient. In investigating how lists and deques work, I found that I can get benefits when I want to shift and unshift reducing the time from O(n) in lists to O(1) in deques (lists being implemented as fixed-length arrays that have to be copied completely each time something is inserted at the front, etc...). What I can't seem to find are the specifics of how a deque is implemented, and the specifics of its downsides v.s. lists. Can someone enlighten me on these two questions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
https://github.com/python/cpython/blob/v3 .8.1/Modules/_collectionsmodule.c
所以是的,正如另一个答案所暗示的那样,双端队列是一个(双向)链表。
详细说明:这意味着 Python 列表更适合随机访问和固定长度操作(包括切片),而双端队列对于从末尾推送和弹出内容更有用,索引(有趣的是,但不包括切片)可能,但比列表慢。
https://github.com/python/cpython/blob/v3.8.1/Modules/_collectionsmodule.c
So yes, a
deque
is a (doubly-)linked list as another answer suggests.Elaborating: What this means is that Python lists are much better for random-access and fixed-length operations, including slicing, while deques are much more useful for pushing and popping things off the ends, with indexing (but not slicing, interestingly) being possible but slower than with lists.
查看
collections.deque
。来自文档:正如它所说,使用 pop(0) 或 insert(0, v) 会对列表对象造成很大的损失。您不能在
deque
上使用切片/索引操作,但可以使用popleft
/appendleft
,它们是操作deque< /code> 已针对以下内容进行了优化。这是一个简单的基准测试来证明这一点:
我的机器上的结果:
Check out
collections.deque
. From the docs:Just as it says, using pop(0) or insert(0, v) incur large penalties with list objects. You can't use slice/index operations on a
deque
, but you can usepopleft
/appendleft
, which are operationsdeque
is optimized for. Here is a simple benchmark to demonstrate this:Results on my machine:
deque
对象 的文档条目阐明了我怀疑你需要知道的大部分内容。值得注意的引言:但...
我必须查看源代码才能判断该实现是链表还是其他东西,但在我看来,
deque
与双向链接具有大致相同的特征列表。The documentation entry for
deque
objects spells out most of what you need to know, I suspect. Notable quotes:But...
I'd have to take a look at the source to tell whether the implementation is a linked list or something else, but it sounds to me as though a
deque
has roughly the same characteristics as a doubly-linked list.除了所有其他有用的答案之外,这里还有一些比较时间复杂度的更多信息(Big-哦)Python 列表、双端队列、集合和字典上的各种操作。这应该有助于为特定问题选择正确的数据结构。
In addition to all the other helpful answers, here is some more information comparing the time complexity (Big-Oh) of various operations on Python lists, deques, sets, and dictionaries. This should help in selecting the right data structure for a particular problem.