【发布时间】:2021-04-18 02:39:45
【问题描述】:
我想遍历并枚举列表的最后几项:
a = [1,2,3,4,5]
[c for c, i in enumerate(a[-3:], -3)] 给出:
[-3, -2, -1]
[c for c, i in enumerate(list(a[-3:]))] 给出:
[0, 1, 2]
[c for c, i in islice(enumerate(a), -5)] 提出:
ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.
那么我该如何枚举:
[3, 4, 5] 使用负索引
?
示例:
for i, j in enumerate(...): print(i,j) 其中... 包含一个只有负索引的切片表达式应该给出:
0 3
1 4
2 5
【问题讨论】:
-
我认为是
enumerate(a[-3:], 3),但不确定您为什么会忽略这一点,所以也许我误解了这个问题。 -
是的,我只想使用负索引。
-
我不确定我是否了解您要查找的内容。您能否编辑问题以包含您想要的输出?
-
在
a中使用字符串而不是数字可能会更清楚。我还是不明白你在这里的意思。你想要enumerate(a, -len(a))吗?
标签: python loops slice itertools enumeration