如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
如果不重新创建一个新列表,你可以通过索引:
>>> foo = ['1a','2b','3c','4d']
>>> for i in range(len(foo)):
... print foo[-(i+1)]
...
4d
3c
2b
1a
>>>
OR
>>> length = len(foo)
>>> for i in range(length):
... print foo[length-i-1]
...
4d
3c
2b
1a
>>>
其他回答
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']
OR
>>> print l[::-1]
['d', 'c', 'b', 'a']
一个简单的方法:
n = int(input())
arr = list(map(int, input().split()))
for i in reversed(range(0, n)):
print("%d %d" %(i, arr[i]))
其他答案都不错,但如果你想这么做 列表理解风格
collection = ['a','b','c']
[item for item in reversed( collection ) ]
作为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 = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
... print(~i, a[~i]))
-1 baz
-2 bar
-3 foo