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

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


当前回答

我喜欢单行生成器方法:

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

其他回答

可以这样做:

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

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

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

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

帮助(范围)

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

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

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

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

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

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

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

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

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