Python的预告倒退了

sha*_*and 8 python foreach python-2.4

python是否有向后推进的方法?我希望能够同时执行filter()(或列表推导)并反转列表,这样我就可以避免单独执行(我怀疑它会更慢).我正在使用python 2.4(我不得不),但我也很好奇列表解析解决方案在python 3.0中会是什么.

编辑这两个解决方案看起来都是一样的:

python -m timeit -s 'x=[1,2,3,4,5]*99; filter(lambda x: x == 5, reversed(x))' 
100000000 loops, best of 3: 0.0117 usec per loop
python -m timeit -s 'x=[1,2,3,4,5]*99; x.reverse(); filter(lambda x: x == 5, x)'    
100000000 loops, best of 3: 0.0117 usec per loop
Run Code Online (Sandbox Code Playgroud)

And*_*ark 20

您正在寻找内置reversed():

>>> for i in reversed(range(5)):
...     print i
... 
4
3
2
1
0
Run Code Online (Sandbox Code Playgroud)

这将反向迭代序列,而不创建列表的其他副本.


Gen*_*cos -1

以下是实现向后迭代可以做的事情的一个很好的汇编:http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html

  • -1:最好至少还提供链接文章的摘要。否则,如果链接断开,这个答案就变得毫无用处。 (8认同)