如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
可以这样做:
for i in range(len(collection)-1, -1, -1):
print collection[i]
# print(collection[i]) for python 3. +
所以你的猜测很接近:)有点尴尬,但它基本上是说:从小于len(collection)的1开始,一直到-1之前,一步一步到-1。
仅供参考,帮助函数非常有用,因为它可以让你从Python控制台查看文档,例如:
帮助(范围)
其他回答
我喜欢单行生成器方法:
((i, sequence[i]) for i in reversed(xrange(len(sequence))))
其他答案都不错,但如果你想这么做 列表理解风格
collection = ['a','b','c']
[item for item in reversed( collection ) ]
如果你不介意指数为负,你可以这样做:
>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
... print(~i, a[~i]))
-1 baz
-2 bar
-3 foo
我很困惑为什么显而易见的选择到目前为止还没有出现:
如果reversed()不能工作,因为你有一个生成器(如enumerate()的情况),只需使用sorted():
>>> l = list( 'abcdef' )
>>> sorted( enumerate(l), reverse=True )
[(5, 'f'), (4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')]
此外,您可以使用“range”或“count”函数。 如下:
a = ["foo", "bar", "baz"]
for i in range(len(a)-1, -1, -1):
print(i, a[i])
3 baz
2 bar
1 foo
你也可以使用itertools中的"count",如下所示:
a = ["foo", "bar", "baz"]
from itertools import count, takewhile
def larger_than_0(x):
return x > 0
for x in takewhile(larger_than_0, count(3, -1)):
print(x, a[x-1])
3 baz
2 bar
1 foo