如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
如何在Python中反向遍历列表?所以我可以从集合[len(collection)-1]开始,到集合[0]结束。
我还希望能够访问循环索引。
当前回答
其他答案都不错,但如果你想这么做 列表理解风格
collection = ['a','b','c']
[item for item in reversed( collection ) ]
其他回答
如果你需要循环索引,并且不想遍历整个列表两次,或者使用额外的内存,我会写一个生成器。
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
我喜欢单行生成器方法:
((i, sequence[i]) for i in reversed(xrange(len(sequence))))
在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)
你可以使用生成器:
li = [1,2,3,4,5,6]
len_li = len(li)
gen = (len_li-1-i for i in range(len_li))
最后:
for i in gen:
print(li[i])
希望这对你有帮助。
>>> l = ["a","b","c","d"]
>>> l.reverse()
>>> l
['d', 'c', 'b', 'a']
OR
>>> print l[::-1]
['d', 'c', 'b', 'a']