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

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


当前回答

def reverse(spam):
    k = []
    for i in spam:
        k.insert(0,i)
    return "".join(k)

其他回答

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

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

你可以:

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

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

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

我喜欢单行生成器方法:

((i, sequence[i]) for i in reversed(xrange(len(sequence))))
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']

OR

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

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