提问者:小点点

在Python中切片列表或字符串对象[重复]


切片中的默认范围是什么:例如:

ls = [1, 2, 3, 4, 5]
ls[-3::1]  #returns copy of the elements at indexes -3, -2, -1
ls[-3::-1] #returns copy of the elements at indexes -3 till the start of the list i.e ls[-5]
ls[::-1]   #returns copy of the reverse version of the list
ls[::1]    #return the list as is

那背后的想法是什么? python如何确定未声明的开始和结束索引?


共2个答案

匿名用户

如果你有一个积极的步骤,那么默认的开始就是开始,默认的结束就是结束。

如果您有一个负的步骤,那么默认的开始是结束,默认的结束是开始。

默认步骤为1。 步骤不能为零。

我想这涵盖了所有的可能性。

匿名用户

例如[a:b:c],因此a是开始索引,b是结束索引,c表示索引之间的步长