gpt4 book ai didi

python - 将Python中的负索引转换为正索引

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:36 24 4
gpt4 key购买 nike

我正在尝试找到一种方法来获取 Python 列表中的项目的索引,给定它的负索引,包括索引 0。

例如,对于大小为 4 的 l 列表:

l[0]  # index 0
l[-1] # index 3
l[-2] # index 2

我试过用

index = negative + len(l)

然而,当索引为 0 时,这将不起作用。

到目前为止,我发现的唯一方法涉及 if/else 语句。

 index = 0 if negative == 0 else negative + len(l)

有没有一种方法可以在 Python 中执行此操作而无需使用 if 语句?

我正在尝试存储项目的索引以便稍后访问它,但我得到的索引从 0 开始并在列表中向后移动,我想将它们从负数转换为正数。

最佳答案

index = 索引模大小

index = index % len(list)

对于大小为 4 的列表,对于给定的索引,它将具有以下值:

 4 -> 0
3 -> 3
2 -> 2
1 -> 1
0 -> 0
-1 -> 3
-2 -> 2
-3 -> 1
-4 -> 0

关于python - 将Python中的负索引转换为正索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com