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

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


当前回答

如果你不介意指数为负,你可以这样做:

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

其他回答

你也可以使用while循环:

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

反转的内置函数很方便:

for item in reversed(sequence):

reverse的文档解释了它的局限性。

对于我必须与索引一起反向遍历序列的情况(例如,对于改变序列长度的原地修改),我有这个函数定义了一个my codeutil模块:

from six.moves import zip as izip, range as xrange

def reversed_enumerate(sequence):
    return izip(
        reversed(xrange(len(sequence))),
        reversed(sequence),
    )

这避免了创建序列的副本。显然,相反的限制仍然适用。

我很困惑为什么显而易见的选择到目前为止还没有出现:

如果reversed()不能工作,因为你有一个生成器(如enumerate()的情况),只需使用sorted():

>>> l = list( 'abcdef' )
>>> sorted( enumerate(l), reverse=True )
[(5, 'f'), (4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')]

你可以:

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

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

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

我喜欢单行生成器方法:

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