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

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


当前回答

你也可以使用while循环:

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

其他回答

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

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

反转的内置函数很方便:

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

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

input_list = ['foo','bar','baz']
for i in range(-1,-len(input_list)-1,-1)
    print(input_list[i])

我认为这也是一种简单的方法……从end开始读取,并一直递减直到列表的长度,因为我们从不执行“end”索引,因此也添加了-1

可以这样做:

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

    # print(collection[i]) for python 3. +

所以你的猜测很接近:)有点尴尬,但它基本上是说:从小于len(collection)的1开始,一直到-1之前,一步一步到-1。

仅供参考,帮助函数非常有用,因为它可以让你从Python控制台查看文档,例如:

帮助(范围)

作为python的初学者,我发现这种方法更容易理解,并且可以反转列表。

= = 1, 2, 3, 4

对于I在range(len(numlst)-1,-1,-1):

ie., for i in range(3,-1,-1), where 3 is length of list minus 1,
second -1 means list starts from last element and 
third -1 signifies it will traverse in reverse order.

打印(numlst[I])

O /p = 4,3,2,1