如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
作为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
其他回答
无论如何,你也可以这样做。非常简单。
a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
x += 1
print a[-x]
无导入的方法:
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)。
你可以在一个普通的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
一个简单的方法:
n = int(input())
arr = list(map(int, input().split()))
for i in reversed(range(0, n)):
print("%d %d" %(i, arr[i]))
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']
OR
>>> print l[::-1]
['d', 'c', 'b', 'a']