[英]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(我尝试的所有时间,不仅仅是这个)
Python 2 and 3 documentation states that the reversed()
built-in function “returns a reverse iterator ”. Python 2和3文档声明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.