好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python内置函数切片

一、切片的定义

 通过索引区间访问线性结构的一段数据  sequence[start:stop] 表示返回[start,stop]区间的子序列,支持负索引  start为0,可以省略,stop为末尾,也可以省略  超过上届(右边界), 就取到末尾;超过下届(左边界),取到开头  [:]表示从头至尾,全部元素被取出,等效于copy()方法

二、切片代码举例

举例:

 >>> s = ‘HdhCmsTestmagedu测试数据‘  >>> s  ‘HdhCmsTestmagedu测试数据‘  >>> s[4:10]  ‘magedu‘  >>> s[:10]  ‘HdhCmsTestmagedu‘  >>> s[4:]  ‘magedu测试数据‘  >>> s[:]  ‘HdhCmsTestmagedu测试数据‘  >>> s[:-1]  ‘HdhCmsTestmagedu.co‘  >>> tuple(s)[-10:10]  (‘m‘, ‘a‘, ‘g‘, ‘e‘, ‘d‘, ‘u‘)  >>> list(s)[-10:4]  []  >>> tuple(s)  (‘w‘, ‘w‘, ‘w‘, ‘.‘, ‘m‘, ‘a‘, ‘g‘, ‘e‘, ‘d‘, ‘u‘, ‘.‘, ‘c‘, ‘o‘, ‘m‘)  >>> list(s)  [‘w‘, ‘w‘, ‘w‘, ‘.‘, ‘m‘, ‘a‘, ‘g‘, ‘e‘, ‘d‘, ‘u‘, ‘.‘, ‘c‘, ‘o‘, ‘m‘]

三、 长步切片

 [start:stop:step],step为步长,可以正、负整数,默认是1  step要和start:stop同向,否则返回空序列

 举例:  >>> s = ‘HdhCmsTestmagedu测试数据‘  >>> s[4:10:2]  ‘mgd‘  >>> list(s)[4:10:-2]  []  >>> tuple(s)[-10:-4:2]  (‘m‘, ‘g‘, ‘d‘)  >>> tuple(s)[-10:-4:-2]  ()  >>> tuple(s)[4:10:2]  (‘m‘, ‘g‘, ‘d‘)  >>> list(‘1234‘)  [‘1‘, ‘2‘, ‘3‘, ‘4‘]

查看更多关于python内置函数切片的详细内容...

  阅读:14次