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

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


当前回答

在python 3中,list创建了一个副本,因此reversed(list(enumerate(collection))可能效率很低,生成的另一个列表没有被优化。

如果collection确实是一个列表,那么最好将复杂性隐藏在迭代器后面

def reversed_enumerate(collection: list):
    for i in range(len(collection)-1, -1, -1):
        yield i, collection[i]

所以,最干净的是:

for i, elem in reversed_enumerate(['foo', 'bar', 'baz']):
    print(i, elem)

其他回答

一个简单的方法:

n = int(input())
arr = list(map(int, input().split()))

for i in reversed(range(0, n)):
    print("%d %d" %(i, arr[i]))

此外,您可以使用“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

你可以在一个普通的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

在python 3中,list创建了一个副本,因此reversed(list(enumerate(collection))可能效率很低,生成的另一个列表没有被优化。

如果collection确实是一个列表,那么最好将复杂性隐藏在迭代器后面

def reversed_enumerate(collection: list):
    for i in range(len(collection)-1, -1, -1):
        yield i, collection[i]

所以,最干净的是:

for i, elem in reversed_enumerate(['foo', 'bar', 'baz']):
    print(i, elem)

其他答案都不错,但如果你想这么做 列表理解风格

collection = ['a','b','c']
[item for item in reversed( collection ) ]