如何在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)
其他回答
无导入的方法:
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)。
作为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
你也可以使用while循环:
i = len(collection)-1
while i>=0:
value = collection[i]
index = i
i-=1
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']
OR
>>> print l[::-1]
['d', 'c', 'b', 'a']
其他答案都不错,但如果你想这么做 列表理解风格
collection = ['a','b','c']
[item for item in reversed( collection ) ]