In [1]: aaa = [1,2,3,4,5]
In [4]: aaa[::-1]
Out[4]: [5, 4, 3, 2, 1]
In [5]: timeit(aaa[::-1])
1000000 loops, best of 3: 206 ns per loop
In [6]: reversed(aaa)
Out[6]: <listreverseiterator at 0x104310d50>
In [7]: timeit(reversed(aaa))
10000000 loops, best of 3: 182 ns per loop
PEP 322: Reverse Iteration A new built-in function, reversed(seq)(),
takes a sequence and returns an iterator that loops over the elements
of the sequence in reverse order.
^{pr2}$
Compared to extended slicing, such as range(1,4)[::-1], reversed() is
easier to read, runs faster, and uses substantially less memory.
Note that reversed() only accepts sequences, not arbitrary iterators.
If you want to reverse an iterator, first convert it to a list with
list().
>>>
>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
... print line
...
反向返回反向迭代器。
x[::-1]返回列表。
reversed
返回反向迭代器。在[::-1]
向对象请求切片Python对象尝试返回您可能期望的结果
这很方便,尤其是对于字符串和元组。在
但请记住,大多数代码不需要反转字符串。在
reversed()
最重要的作用是使代码更易于阅读和理解。在它返回迭代器而不创建新序列的事实是次要的
From the docs
^{pr2}$第一种表示法是急切地生成反向;第二种表示法是给您一个反向迭代器,这可能更便宜,因为它有可能只在需要时生成元素
相关问题 更多 >
编程相关推荐