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

将Python中的负索引转换为正索引,python,list,indexing,Python,List,Indexing,我试图找到一种方法来获取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中有没有一种

我试图找到一种方法来获取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 = len(l) - index - 1
计算“从后面开始的索引”

在许多其他编程语言中都必须这样做。蟒蛇的负指数只是句法上的糖分

但是如果你真的使用负指数,这个肮脏的黑客是一个没有
if
else
的单行程序:

index = int(negative != 0 and negative + len(l))
说明:

  • 如果
    negative==0
    表达式的结果为
    False
    ,通过调用
    int
    将其转换为
    0
  • 否则,
    的结果为
    负+len
    ,另请参阅。调用
    int
    则什么也不做

这有助于学习Python,但我通常避免使用此类技巧。对于你和其他人来说,它们很难阅读,也许你想在几个月后再次阅读你的程序,然后你会想知道这一行在做什么。

负指数等于从长度中减去:

>> lst = [1, 2, 3]
>> lst[-1] == lst[len(lst) - 1]
True
所以你可以用一个小的if语句得到一个总是正值:

i = -2
index = i if number >= 0 else len(lst) - i 
事实上,如果长度大于列表的长度,则可以使用“模数”将索引换回0:

# assuming length of list is 4
index = i % len(list)

# with i at 0:
0 % 4 == 0 # that works

# with i as -2
-2 % 4 == 2 # that works

# with i as 3:
3 % 4 == 3 % # that works

您可以使用
~
补码运算符。它将根据需要为您提供反向索引

>>> l = ["a", "b", "c", "d"]
>>> l[0]
'a'
>>> l[~0]
'd'
>>> l[~3]
'a'
>>> l[~-1]
'a'
>>> l[-1]
'd'

索引=索引模大小

index = index % len(list)
对于大小为4的列表,给定索引的值如下:

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

是否只想将索引转换为正数?如果您想访问数组,python会自行进行访问滚动,但是我的问题是索引为0:lst[0]==lst[len(lst)-0]
索引器:使用三元If语句列出索引超出范围
避免了这一点,因为
else
部分仅在索引小于0时进行计算,不是0itself@ducminhif语句中的条件不同您也可以使用
index%=len(list)
,条件相同: