Python元组切片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21128845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:07:30  来源:igfitidea点击:

Python Tuple Slicing

pythontuplesslice

提问by KGS

Given that -1 goes back to the first term in a tuple, and the end index of a slice stops before that index, why does

鉴于 -1 返回元组中的第一项,并且切片的结束索引在该索引之前停止,为什么

x=(1,2,3,4,5)
x[0:-1]

yield

屈服

(1, 2, 3, 4)

instead of stopping at the index before the first which is 5?

而不是在第一个 5 之前的索引处停止?

Thanks

谢谢

采纳答案by twj

-1 does not go back to the first term in a tuple

-1 不会回到元组中的第一项

x=(1,2,3,4,5)
x[-1]

yields

产量

5

回答by Christian

Slicing works like this:

切片的工作方式如下:

x[start : end : step]

In your example, start = 0, so it will start from the beginning, end = -1it means that the end will be the last element of the tuple (not the first). You are not specifying stepso it will its default value 1.

在您的示例中,start = 0,因此它将从头开始,end = -1这意味着结尾将是元组的最后一个元素(不是第一个)。您没有指定,step因此它将是其默认值1

This link from Python docsmay be helpful, there are some examples of slicing.

Python 文档中的链接可能会有所帮助,其中有一些切片示例。

回答by John La Rooy

It helps to think of the slicing points as betweenthe elements

它有助于将切片点视为元素之间

x = (   1,   2,   3,   4,   5   )
      |    |    |    |    |    |
      0    1    2    3    4    5
     -5   -4   -3   -2   -1

回答by aady

A -ve value in any python sequences means :

任何 python 序列中的 -ve 值意味着:

Val = len(sequence)+(-ve value)

Either start/stop from/to len(sequence)+(-ve value), depending on what we specify.

开始/停止 from/to len(sequence)+(-ve value),取决于我们指定的内容。