如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
def reverse(spam):
k = []
for i in spam:
k.insert(0,i)
return "".join(k)
其他回答
此外,您可以使用“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
无导入的方法:
for i in range(1,len(arr)+1):
print(arr[-i])
时间复杂度O(n)和空间复杂度O(1)。
一种在内存中创建新列表的方法,使用大列表时要小心:
for i in arr[::-1]:
print(i)
时间复杂度O(n)和空间复杂度O(n)。
使用list.reverse(),然后像往常一样迭代。
http://docs.python.org/tutorial/datastructures.html
要使用负标:从-1开始,在每次迭代中后退-1。
>>> a = ["foo", "bar", "baz"]
>>> for i in range(-1, -1*(len(a)+1), -1):
... print i, a[i]
...
-1 baz
-2 bar
-3 foo
可以这样做:
for i in range(len(collection)-1, -1, -1):
print collection[i]
# print(collection[i]) for python 3. +
所以你的猜测很接近:)有点尴尬,但它基本上是说:从小于len(collection)的1开始,一直到-1之前,一步一步到-1。
仅供参考,帮助函数非常有用,因为它可以让你从Python控制台查看文档,例如:
帮助(范围)