如何在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
其他回答
使用内置的reversed()函数:
>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
要访问原始索引,在将其传递给reversed()之前,在列表中使用enumerate():
>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
由于enumerate()返回一个生成器,而生成器不能反转,因此需要首先将其转换为一个列表。
我喜欢单行生成器方法:
((i, sequence[i]) for i in reversed(xrange(len(sequence))))
你可以在一个普通的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
如果你需要索引,而你的列表很小,最易读的方法是像公认的答案所说的那样做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)
可以这样做:
for i in range(len(collection)-1, -1, -1):
print collection[i]
# print(collection[i]) for python 3. +
所以你的猜测很接近:)有点尴尬,但它基本上是说:从小于len(collection)的1开始,一直到-1之前,一步一步到-1。
仅供参考,帮助函数非常有用,因为它可以让你从Python控制台查看文档,例如:
帮助(范围)