取一个list或tuple的部分元素是非常常见的操作,比如,一个list如下
L = ['Michael','Sraah','Tracy','xiaoming','xiaohua']
取前3个元素,在python提供了切片(Slice)操作符
即L[0:3] 表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,这3个元素
L[0:3]
['Michael', 'Sraah', 'Tracy']
如果第一个索引是0,还可以省略:
>>> L[:3]
['Michael', 'Sraah', 'Tracy']
>>> L[:-1]
['Michael', 'Sraah', 'Tracy', 'xiaoming']
>>> L[-1:]
['xiaohua']
>>> L[-2] 倒数第二个
'xiaoming'
>>> L[-2:] 倒数第2个之后的
['xiaoming', 'xiaohua']
>>> L[:-2] 倒数第2个之前的
['Michael', 'Sraah', 'Tracy']
>>> l = list(range(100))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> l[:10:2] 前10个,每2个取一个
[0, 2, 4, 6, 8]
>>> l[::5] 所有的,每5个取一个
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
关于字符串的截取操作
>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'
网友评论