[英]-1 index in array?
I am trying to use:我正在尝试使用:
num_new = num[i,-1]
to get the last segment of the array.获取数组的最后一段。 However, it returns
[]
when i = 0
, and num = [3]
但是,它在
i = 0
和num = [3]
时返回[]
num = [3]
Do I have to use like num[i, len(num)]
?我必须使用像
num[i, len(num)]
吗? Is there any other attention need to pay when using -1
to retrieve array elements?使用
-1
检索数组元素时还有什么需要注意的吗?
I think this is not a matter of -1, but python list slicing.我认为这不是 -1 的问题,而是 python 列表切片的问题。
some_list[-n]
means n
th element of list from end of list, so you will get 5 as a result in following example: some_list[-n]
表示从列表末尾开始的第n
个元素,因此在以下示例中您将获得 5 作为结果:
some_list = [1, 3, 5]
last_elem = some_list[-1] # 5
And this is not a core issue of your question.这不是你问题的核心问题。
List slicing in python works with this args: python中的列表切片适用于这个参数:
some_list[_start_:_end_:_step_]
And end th element is exclusive .而end th 元素是独家的。
So if you are trying to [3][0:-1], this excludes last element and returns empty list.因此,如果您尝试 [3][0:-1],这将排除最后一个元素并返回空列表。
If you want to get last segment of list, you should slice like this:如果你想得到列表的最后一段,你应该像这样切片:
some_list = [1, 2, 3, 4, 5]
sliced_list = some_list[3:] # [4, 5]
neg_1_list = some_list[3:-1] # [4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.