简体   繁体   English

在Python中有效地在两个方向上迭代双端队列

[英]iterating over a deque in two directions efficiently in Python

I have a deque, let's call it deq . 我有一个双端队列,我们​​称之为deq I need to iterate over it from both ends, and I will not be modifying it at all during these iterations. 我需要从两端迭代它,在这些迭代期间我根本不会修改它。

Naturally, I don't want to create another deque. 当然,我不想创造另一个双端队列。 I've considered reversed , but I don't know if it actually creates any copies. 我考虑过reversed ,但我不知道它是否真的创造了任何副本。 If, for example, I were write: 例如,如果我写的是:

reversed_deq = reversed(deq)

will it reference the exact same memory locations, but simply iterate over it in reverse, without using any more memory/time? 它会引用完全相同的内存位置,但只是反向迭代它,而不使用更多的内存/时间吗?

That seems like the logical way to go for a double-ended queue, but I want to make sure I'm not missing anything. 这似乎是采用双端队列的合理方式,但我想确保我没有遗漏任何东西。

I can't find the code for deque (usually they have a "python equivalent" of these things, but I couldn't find it), and for some reason - no matter what I run - timeit always gives me something between 15 and 16 ns (for everything I try to time, not just this) 我找不到deque的代码(通常他们有这些东西的“python等价物”,但是我找不到它),并且由于某种原因 - 无论我跑什么 - timeit总是给我15到15之间的东西16 ns(我尝试的所有时间,不仅仅是这个)

From the C source reversed([deque]) returns a reverse iterator, no copies or memory allocation. C源逆转([deque])返回一个反向迭代器,没有副本或内存分配。 [deque].reverse() will reverse it in place. [deque] .reverse()会将其反转到位。

Python 2 and 3 documentation states that the reversed() built-in function “returns a reverse iterator ”. Python 23文档声明reverse reversed()内置函数“返回反向迭代器 ”。 Strictly speaking, this does not prevent an implementation of collections.deque.__reversed__() to make copies. 严格来说,这并不妨碍collections.deque.__reversed__()来制作副本。 In practice, there is no reason why it would make copies, since a deque is naturally iterable in both directions. 在实践中,没有理由为什么它会复制,因为双端队列在两个方向上都是自然可迭代的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM