小编Ili*_*bev的帖子

逆枚举列表的最pythonic方法是什么?

首先想到的是:

>>> l = list('abcdef')
>>> for i in range(len(l)-1, -1, -1):
...   item = l[i]
...   print(i, item)
...
5 f
4 e
3 d
2 c
1 b
0 a
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下方法:

>>> l
['a', 'b', 'c', 'd', 'e', 'f']
>>> for i,ch in reversed(enumerate(l)):
...   print(i,ch)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'enumerate' object is not reversible
Run Code Online (Sandbox Code Playgroud)

但显然“枚举”对象是不可逆的。我可以用以下方法欺骗它:

>>> for i,ch in reversed(list(enumerate(l))):
...   print(i,ch)
...
5 f
4 e
3 …
Run Code Online (Sandbox Code Playgroud)

python

9
推荐指数
1
解决办法
2074
查看次数

标签 统计

python ×1