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

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


当前回答

无论如何,你也可以这样做。非常简单。

a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
    x += 1
    print a[-x]

其他回答

>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

OR

>>> print l[::-1]
['d', 'c', 'b', 'a']

你可以:

for item in my_list[::-1]:
    print item

(或者你想在for循环中做的任何事情。)

[::-1]片在for循环中反转列表(但实际上不会“永久”修改列表)。

在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)

如果不重新创建一个新列表,你可以通过索引:

>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
...     print foo[-(i+1)]
...
4d
3c
2b
1a
>>>

OR

>>> length = len(foo)
>>> for i in range(length):
...     print foo[length-i-1]
...
4d
3c
2b
1a
>>>

无导入的方法:

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)。