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

问题描述

所以我可以从 collection[len(collection)-1] 开始到 collection[0] 结束.

我也希望能够访问循环索引.

解决方案

使用内置的 reversed() 函数:

>>>a = ["foo", "bar", "baz"]>>>对于 i in reversed(a):...打印(一)...巴兹酒吧富

要访问原始索引,请使用 enumerate() 在您的列表中,然后将其传递给 reversed():

>>>对于 i, e in reversed(list(enumerate(a))):... 打印(i,e)...2巴兹1 巴0 富

由于enumerate()返回的是一个生成器,生成器不能反转,所以需要先将其转换为list.

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

I also want to be able to access the loop index.

解决方案

Use the built-in reversed() function:

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

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

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