Python切片
-
用切边可以选取大多数序列类型的一部分,切片的基本形式是在方括号中使用start:stop
In [73]: seq = [7, 2, 3, 7, 5, 6, 0, 1]
In [74]: seq[1:5]
Out[74]: [2, 3, 7, 5]
***注:***切片元素的个数为stop - start。切片的起始元素是包括的,不包含结束元素。 -
切片也可以被序列赋值:
In [75]: seq[3:4] = [6, 3]
In [76]: seq
Out[76]: [7, 2, 3, 6, 3, 5, 6, 0, 1]seq[1:4]=[8,8,8,8]
In [38]: seq
Out[38]: [7, 8, 8, 8, 8, 3, 5, 6, 0, 1]
***注:***赋值元素的个数为stop – start+1.被赋值后的列表元素从stop开始罗列。 -
start或stop都可以被省略,省略之后,分别默认序列的开头和结尾:
In [77]: seq[:5]
Out[77]: [7, 2, 3, 6, 3]
In [78]: seq[3:]
Out[78]: [6, 3, 5, 6, 0, 1]
负数表明从后向前切片:
In [79]: seq[-4:]
Out[79]: [5, 6, 0, 1]
In [80]: seq[-6:-2]
Out[80]: [6, 3, 5, 6] -
图解切片
-
在第二个冒号后面使用step,可以隔一个取一个元素:
In [81]: seq[::2]
Out[81]: [7, 3, 3, 6, 1]
一个聪明的方法是使用-1,它可以将列表或元组颠倒过来:
In [82]: seq[::-1]
Out[82]: [1, 0, 6, 5, 3, 6, 3, 2, 7]