Question

Does python have a means of doing foreach backwards? I'm hoping to do a filter() (or list comprehension) and reverse a list at the same time, so that I can avoid doing it separately (which I suspect will be slower). I'm using python 2.4 (I have to unfortunately), but I'm also curious what the list comprehension solution would be in python 3.0.

Edit Both of these solutions appear to be the same:

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
Était-ce utile?

La solution

Here is a good compilation of things you could do to achieve backward iteration: http://christophe-simonis-at-tiny.blogspot.com/2008/08/python-reverse-enumerate.html

Autres conseils

You are looking for the built-in reversed():

>>> for i in reversed(range(5)):
...     print i
... 
4
3
2
1
0

This iterates over the sequence in reverse, without creating an additional copy of your list.

It is not the right way to do it in the same time with filtering. Just use reverse, it will be much more optimized than doing it manually.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top