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

cpx*_*pxn 3 python indexing list

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

例如,使用列表l,大小为4:

l[0]  # index 0
l[-1] # index 3
l[-2] # index 2
Run Code Online (Sandbox Code Playgroud)

我试过用

index = negative + len(l)
Run Code Online (Sandbox Code Playgroud)

但是当索引时这不起作用0.

到目前为止,我找到的唯一方法是if/else发表声明.

 index = 0 if negative == 0 else negative + len(l)
Run Code Online (Sandbox Code Playgroud)

有没有办法在Python中执行此操作而不必使用if语句?

我正在尝试存储项目的索引,以便我可以稍后访问它,但是我被给予从0开始并从列表向后移动的索引,并且希望将它们从负转换为正.

Jit*_*a A 6

index =索引模数大小

index = index % len(list)
Run Code Online (Sandbox Code Playgroud)

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

 4 -> 0
 3 -> 3
 2 -> 2
 1 -> 1 
 0 -> 0
-1 -> 3
-2 -> 2
-3 -> 1
-4 -> 0
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用`index %= len(list)`,它是相同的:https://www.w3schools.com/python/python_operators.asp (2认同)