本文介绍了在Python中以相反的顺序遍历列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我可以从len(collection)开始并以collection[0]结尾.

So I can start from len(collection) and end in collection[0].

对不起,我忘了提及我也希望能够访问循环索引.

Sorry, I forgot to mention I also want to be able to access the loop index.

推荐答案

使用内置的 reversed() 函数:

Use the built-in reversed() function:

>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
...     print(i)
...
baz
bar
foo

要访问原始索引,请在列表上使用 enumerate() 在将其传递给reversed()之前:

To also access the original index, use enumerate() on your list before passing it to reversed():

>>> for i, e in reversed(list(enumerate(a))):
...     print(i, e)
...
2 baz
1 bar
0 foo

由于enumerate()返回一个生成器并且生成器无法反转,因此您需要先将其转换为list.

Since enumerate() returns a generator and generators can't be reversed, you need to convert it to a list first.

这篇关于在Python中以相反的顺序遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:18