如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
你也可以使用while循环:
i = len(collection)-1
while i>=0:
value = collection[i]
index = i
i-=1
其他回答
如果你需要循环索引,并且不想遍历整个列表两次,或者使用额外的内存,我会写一个生成器。
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
其他答案都不错,但如果你想这么做 列表理解风格
collection = ['a','b','c']
[item for item in reversed( collection ) ]
如果你需要索引,而你的列表很小,最易读的方法是像公认的答案所说的那样做reversed(list(enumerate(your_list))。但这将创建列表的副本,因此如果列表占用了很大一部分内存,则必须从len()-1中减去enumerate(reversed())返回的下索引。
如果你只需要做一次:
a = ['b', 'd', 'c', 'a']
for index, value in enumerate(reversed(a)):
index = len(a)-1 - index
do_something(index, value)
或者如果你需要多次这样做,你应该使用生成器:
def enumerate_reversed(lyst):
for index, value in enumerate(reversed(lyst)):
index = len(lyst)-1 - index
yield index, value
for index, value in enumerate_reversed(a):
do_something(index, value)
你也可以使用while循环:
i = len(collection)-1
while i>=0:
value = collection[i]
index = i
i-=1
我喜欢单行生成器方法:
((i, sequence[i]) for i in reversed(xrange(len(sequence))))