如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
在python 3中,list创建了一个副本,因此reversed(list(enumerate(collection))可能效率很低,生成的另一个列表没有被优化。
如果collection确实是一个列表,那么最好将复杂性隐藏在迭代器后面
def reversed_enumerate(collection: list):
for i in range(len(collection)-1, -1, -1):
yield i, collection[i]
所以,最干净的是:
for i, elem in reversed_enumerate(['foo', 'bar', 'baz']):
print(i, elem)
其他回答
反转的内置函数很方便:
for item in reversed(sequence):
reverse的文档解释了它的局限性。
对于我必须与索引一起反向遍历序列的情况(例如,对于改变序列长度的原地修改),我有这个函数定义了一个my codeutil模块:
from six.moves import zip as izip, range as xrange
def reversed_enumerate(sequence):
return izip(
reversed(xrange(len(sequence))),
reversed(sequence),
)
这避免了创建序列的副本。显然,相反的限制仍然适用。
你也可以使用while循环:
i = len(collection)-1
while i>=0:
value = collection[i]
index = i
i-=1
无论如何,你也可以这样做。非常简单。
a = [1, 2, 3, 4, 5, 6, 7]
for x in xrange(len(a)):
x += 1
print a[-x]
一个简单的方法:
n = int(input())
arr = list(map(int, input().split()))
for i in reversed(range(0, n)):
print("%d %d" %(i, arr[i]))
反向函数在这里很方便:
myArray = [1,2,3,4]
myArray.reverse()
for x in myArray:
print x