-1数组索引?

huangapple go评论78阅读模式
英文:

-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 nth 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.

huangapple
  • 本文由 发表于 2020年1月7日 01:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定