how to loop down in python list (countdown)
how to loop down in python list?
for ex开发者_StackOverflowample
loop:
L = [1,2,3]
for item in L
print item #-->1,2,3
loop down:
L = [1,2,3]
for ???
print item #-->3,2,1
thank you
Batteries included.
for i in reversed([1, 2, 3]):
print i
Slicing the list (ls[::-1]
) is great for making a reversed copy, but on my machine it's slower for iteration, even if the list is already in memory:
>>> def sliceit(x):
... l = range(x)
... for i in l[::-1]:
... i
...
>>> def reverseit(x):
... l = range(x)
... for i in reversed(l):
... i
...
>>> %timeit sliceit(100)
100000 loops, best of 3: 4.04 µs per loop
>>> %timeit reverseit(100)
100000 loops, best of 3: 3.79 µs per loop
>>> %timeit sliceit(1000)
10000 loops, best of 3: 34.9 µs per loop
>>> %timeit reverseit(1000)
10000 loops, best of 3: 32.5 µs per loop
>>> %timeit sliceit(10000)
1000 loops, best of 3: 364 µs per loop
>>> %timeit reverseit(10000)
1000 loops, best of 3: 331 µs per loop
As is often true in cases like these, the difference is pretty negligible. It might be different for different versions of Python (I used Python 2.7 for the above test). The real benefit of using reversed
is readability -- it would be preferable in most cases even if it cost a couple of extra microseconds.
Reverse the sequence.
L = [1,2,3]
for item in reversed(L)
print item #-->3,2,1
Another solution:
for item in L[::-1]:
print item
I know this thread is now years old, but a comment under the accepted answer contains the claim that using [::-1]
is faster than using reversed()
. This is only true if your list is explicitly put into memory, which is not necessary when doing a countdown. Otherwise it is slower:
>>> timeit.Timer(stmt="range(1,1000)[::-1]").timeit()
10.801303316066111
>>> timeit.Timer(stmt="list(reversed(xrange(1,1000)))").timeit()
9.484562358901144
...and [::-1]
uses more space than reversed
.
精彩评论