如何在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
>>>
其他回答
你可以使用生成器:
li = [1,2,3,4,5,6]
len_li = len(li)
gen = (len_li-1-i for i in range(len_li))
最后:
for i in gen:
print(li[i])
希望这对你有帮助。
可以这样做:
for i in range(len(collection)-1, -1, -1):
print collection[i]
# print(collection[i]) for python 3. +
所以你的猜测很接近:)有点尴尬,但它基本上是说:从小于len(collection)的1开始,一直到-1之前,一步一步到-1。
仅供参考,帮助函数非常有用,因为它可以让你从Python控制台查看文档,例如:
帮助(范围)
你可以:
for item in my_list[::-1]:
print item
(或者你想在for循环中做的任何事情。)
[::-1]片在for循环中反转列表(但实际上不会“永久”修改列表)。
如果不重新创建一个新列表,你可以通过索引:
>>> 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
>>>
一个简单的方法:
n = int(input())
arr = list(map(int, input().split()))
for i in reversed(range(0, n)):
print("%d %d" %(i, arr[i]))