Python中14个切片操作,你常用哪几个?
切片(Slice)是一个取部分元素的操作,是Python中特有的功能。它可以操作list、tuple、字符串。
Python的切片非常灵活,一行代码就可以实现很多行循环才能完成的操作。切片操作的三个参数 [start: stop: step] ,其中start是切片的起始位置,stop是切片的结束位置(不包括),step可以不提供,默认值是1,并且step可为负数(详细使用见下)
下面盘点下切片的常见操作。
1.切取的元素不包括右端点


2.切片左端点为0,可省略

3.每两个取一个

4.支持倒数切片,倒数第一个元素的索引是-1

5.原样复制一个list

6.起始索引和终止索引都省略,也就都为默认值,如下步长设置为2切取元素

7.一行代码实现列表反转

8.步长为负数,实际上指明了一个逆向迭代器。如下逆向倒数,每两个取一个。

9.值得注意,Python超出索引范围不报错

10.步长step为0,会报错

11.切片操作的三个参数可以用表达式

12.连续切片操作

13.元组对象的切片操作

相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16