def reverse_enum(L):for index in reversed(xrange(len(L))):yield index, L[index]
L = ['foo', 'bar', 'bas']for index, item in reverse_enum(L):print index, item
a = ["foo", "bar", "baz"]for i in range(len(a)-1, -1, -1):print(i, a[i])
3 baz2 bar1 foo
您还可以使用iterols中的“计数”,如下所示:
a = ["foo", "bar", "baz"]from itertools import count, takewhile
def larger_than_0(x):return x > 0
for x in takewhile(larger_than_0, count(3, -1)):print(x, a[x-1])
3 baz2 bar1 foo
a = ['b', 'd', 'c', 'a']
for index, value in enumerate(reversed(a)):index = len(a)-1 - index
do_something(index, value)
或者如果你需要多次这样做,你应该使用生成器:
def enumerate_reversed(lyst):for index, value in enumerate(reversed(lyst)):index = len(lyst)-1 - indexyield index, value
for index, value in enumerate_reversed(a):do_something(index, value)
>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))4.6937971115112305>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))4.809093952178955>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))4.931743860244751>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))5.548468112945557>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))6.286104917526245>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n i -= 1\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))8.384078979492188
所以,最丑的选项xrange(len(xs)-1,-1,-1)是最快的。
Python 3(不同的机器):
>>> timeit.timeit('for i in range(len(xs)-1,-1,-1):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', number=400000)4.48873088900001>>> timeit.timeit('for i in reversed(range(0, len(xs))):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', number=400000)4.540959084000008>>> timeit.timeit('for i, x in enumerate(reversed(xs), 1):\n if 128 == x: break', setup='xs, n = range(256), 0', number=400000)1.9069805409999958>>> timeit.timeit('for i, x in enumerate(xs[::-1]):\n if 128 == x: break', setup='xs, n = range(256), 0', number=400000)2.960720073999994>>> timeit.timeit('for i in range(len(xs), 0, -1):\n if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', number=400000)5.316207007999992>>> timeit.timeit('i = len(xs)\nwhile 0 < i:\n i -= 1\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', number=400000)5.802550058999998
ie., for i in range(3,-1,-1), where 3 is length of list minus 1,second -1 means list starts from last element andthird -1 signifies it will traverse in reverse order.