英文:
-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]
Do I have to use like num[i, len(num)]
?
Is there any other attention need to pay when using -1
to retrieve array elements?
英文:
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]
Do I have to use like num[i, len(num)]
?
Is there any other attention need to pay when using -1
to retrieve array elements?
答案1
得分: 1
some_list[-n]
表示列表中倒数第 n
个元素,因此在以下示例中,您会得到结果为 5:
some_list = [1, 3, 5]
last_elem = some_list[-1] # 5
这不是您问题的核心问题。
Python 中的列表切片使用以下参数工作:
some_list[_start_:_end_:_step_]
其中 end 元素是不包括的。
因此,如果您尝试 [3][0:-1]
,这会排除最后一个元素并返回空列表。
如果您想要获取列表的最后一段,应该像这样切片:
some_list = [1, 2, 3, 4, 5]
sliced_list = some_list[3:] # [4, 5]
neg_1_list = some_list[3:-1] # [4]
这里 会帮助您。
英文:
I think this is not a matter of -1, but python list slicing.
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 = [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:
some_list[_start_:_end_:_step_]
And end th element is exclusive.
So if you are trying to [3][0:-1], this excludes last element and returns empty list.
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]
This will help you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论