如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
如果你需要循环索引,并且不想遍历整个列表两次,或者使用额外的内存,我会写一个生成器。
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(1,len(arr)+1):
print(arr[-i])
时间复杂度O(n)和空间复杂度O(1)。
一种在内存中创建新列表的方法,使用大列表时要小心:
for i in arr[::-1]:
print(i)
时间复杂度O(n)和空间复杂度O(n)。
反转的内置函数很方便:
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
此外,您可以使用“range”或“count”函数。 如下:
a = ["foo", "bar", "baz"]
for i in range(len(a)-1, -1, -1):
print(i, a[i])
3 baz
2 bar
1 foo
你也可以使用itertools中的"count",如下所示:
a = ["foo", "bar", "baz"]
from itertools import count, takewhile
def larger_than_0(x):
return x > 0
for x in takewhile(larger_than_0, count(3, -1)):
print(x, a[x-1])
3 baz
2 bar
1 foo
其他答案都不错,但如果你想这么做 列表理解风格
collection = ['a','b','c']
[item for item in reversed( collection ) ]