问题描述:
列表切片索引sequence[start:end:step],当切片处于起始位置0时,start可以省略不写,当切片处于终止位置时,end可以省略不写,step步长为1时,可以省略不写。
问题解答:
列表切片在 Python 中的索引表示方式是 sequence[start:end:step]
,其中:
start
:起始索引,表示从哪里开始切片。如果省略,则默认为列表的开头(索引 0)。end
:结束索引,表示切片到哪里结束(不包括该索引处的元素)。如果省略,则默认为列表的末尾。step
:步长,表示每次取元素时跨越的步数。如果省略,则默认为 1。
下面是一些具体的例子来说明这些情况:
-
省略
start
:ls = ["a", "b", "c", "d"] print(ls[:2]) # 输出 ['a', 'b']
-
省略
end
:ls = ["a", "b", "c", "d"] print(ls[2:]) # 输出 ['c', 'd']
-
省略
step
:ls = ["a", "b", "c", "d"] print(ls[1:3]) # 输出 ['b', 'c']
-
省略
start
和end
:ls = ["a", "b", "c", "d"] print(ls[::2]) # 输出 ['a', 'c']
-
省略
start
和step
:ls = ["a", "b", "c", "d"] print(ls[:3]) # 输出 ['a', 'b', 'c']
-
省略
end
和step
:ls = ["a", "b", "c", "d"] print(ls[1:]) # 输出 ['b', 'c', 'd']
-
省略
start
,end
和step
:ls = ["a", "b", "c", "d"] print(ls[:]) # 输出 ['a', 'b', 'c', 'd']
这里,省略了
start
,end
和step
,所以默认返回整个列表。
总结:
start
可以省略不写,默认从列表开头开始切片。end
可以省略不写,默认切片到列表末尾。step
可以省略不写,默认步长为 1。