如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。

我还希望能够访问循环索引。


当前回答

我喜欢单行生成器方法:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))

其他回答

如果你需要循环索引,并且不想遍历整个列表两次,或者使用额外的内存,我会写一个生成器。

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

你可以在一个普通的for循环中使用一个负索引:

>>> collection = ["ham", "spam", "eggs", "baked beans"]
>>> for i in range(1, len(collection) + 1):
...     print(collection[-i])
... 
baked beans
eggs
spam
ham

要访问索引,就像在集合的反向副本上向前迭代一样,使用i - 1:

>>> for i in range(1, len(collection) + 1):
...     print(i-1, collection[-i])
... 
0 baked beans
1 eggs
2 spam
3 ham

要访问未反转的原始索引,使用len(collection) - i:

>>> for i in range(1, len(collection) + 1):
...     print(len(collection)-i, collection[-i])
... 
3 baked beans
2 eggs
1 spam
0 ham

无导入的方法:

for i in range(1,len(arr)+1):
    print(arr[-i])

时间复杂度O(n)和空间复杂度O(1)。

一种在内存中创建新列表的方法,使用大列表时要小心:

for i in arr[::-1]:
    print(i)

时间复杂度O(n)和空间复杂度O(n)。

此外,您可以使用“range”或“count”函数。 如下:

a = ["foo", "bar", "baz"]
for i in range(len(a)-1, -1, -1):
    print(i, a[i])

3 baz
2 bar
1 foo

你也可以使用itertools中的"count",如下所示:

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 baz
2 bar
1 foo

你也可以使用while循环:

i = len(collection)-1
while i>=0:
    value = collection[i]
    index = i
    i-=1