如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
你可以在一个普通的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
其他回答
反向函数在这里很方便:
myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x
要使用负标:从-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
如果你需要循环索引,并且不想遍历整个列表两次,或者使用额外的内存,我会写一个生成器。
def reverse_enum(L):
for index in reversed(xrange(len(L))):
yield index, L[index]
L = ['foo', 'bar', 'bas']
for index, item in reverse_enum(L):
print index, item
可以这样做:
for i in range(len(collection)-1, -1, -1):
print collection[i]
# print(collection[i]) for python 3. +
所以你的猜测很接近:)有点尴尬,但它基本上是说:从小于len(collection)的1开始,一直到-1之前,一步一步到-1。
仅供参考,帮助函数非常有用,因为它可以让你从Python控制台查看文档,例如:
帮助(范围)
一个简单的方法:
n = int(input())
arr = list(map(int, input().split()))
for i in reversed(range(0, n)):
print("%d %d" %(i, arr[i]))