Python高级特性切片(Slice)操作详解
作者:扉亦般先生 时间:2022-04-07 20:28:02
切片操作首先支持下标索引,通过[ N:M :P ]操作
索引正向从0开始,逆向从-1开始
N:切片开始位置
M:切片结束位置(不包含)
P:指定切片步长,为正数表示按照指定步长正向切片,为负数反之
一、列表的切片操作
列表切片后还是列表
通过列表生成器定义一个列表:
In [2]: a = [n for n in range(10)]
In [3]: a
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
通过切片浅拷贝对象:
In [4]: a[:]
Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [5]: a[::]
Out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
指定开始切片位置:
In [6]: a[1:]
Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [7]: a[1::]
Out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
指定切片范围(不包含结束):
In [8]: a[1:5]
Out[8]: [1, 2, 3, 4]
In [9]: a[2:6:]
Out[9]: [2, 3, 4, 5]
指定步长切片:
In [10]: a[0:9:3]
Out[10]: [0, 3, 6]
In [11]: a[0:9:2]
Out[11]: [0, 2, 4, 6, 8]
指定步长方向:
In [12]: a[9:0:-2]
Out[12]: [9, 7, 5, 3, 1]
In [13]: a[9:0:-3]
Out[13]: [9, 6, 3]
通过切片逆置列表:
In [15]: a[::-1]
Out[15]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
二、元组切片
元组切片后还是元组,用法和列表切片一样,但是一点需要注意
In [17]: b = (n for n in range(5))
In [18]: b
Out[18]: <generator object <genexpr> at 0x00000206445ED780>
# 推到式通过小括号()以后就不是元组了,是生成器的另一种形式
In [19]: b = tuple(n for n in range(5))
In [20]: b
Out[20]: (0, 1, 2, 3, 4)
In [21]: b[::-1]
Out[21]: (4, 3, 2, 1, 0)
In [22]: b[0:2:]
Out[22]: (0, 1)
三、字符串切片
字符串切片之后还是字符串,用法也和列表切片一致
In [23]: c = "hello,world"
In [24]: c[::-1]
Out[24]: 'dlrow,olleh'
In [25]: c[0:5:]
Out[25]: 'hello'
来源:http://blog.51cto.com/10412806/2286322
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python烟花效果的代码实例
![](https://img.aspxhome.com/file/2023/6/89096_0s.gif)
备战618!用Python脚本帮你实现淘宝秒杀
![](https://img.aspxhome.com/file/2023/4/78674_0s.png)
Django使用channels + websocket打造在线聊天室
![](https://img.aspxhome.com/file/2023/9/76729_0s.gif)
sql分类汇总及Select的自增长脚本
google 的设计原则和LOGO手绘
![](https://img.aspxhome.com/file/UploadPic/20085/20/2008520122313977s.gif)
详解django中自定义标签和过滤器
![](https://img.aspxhome.com/file/2023/3/75883_0s.png)
asp实现树型结构
Python Matplotlib初阶使用入门教程
![](https://img.aspxhome.com/file/2023/9/99169_0s.png)
解决缩小图标变样问题
![](https://img.aspxhome.com/file/UploadPic/200710/8/2007108191659246s.png)
利用Anaconda完美解决Python 2与python 3的共存问题
em和strong的区别
利用Python实现自动扫雷小脚本
![](https://img.aspxhome.com/file/2023/7/84977_0s.jpg)
Python3 实现爬取网站下所有URL方式
Django模板继承与模板的导入实例详解
![](https://img.aspxhome.com/file/2023/3/92143_0s.gif)
Python实现简易端口扫描器代码实例
![](https://img.aspxhome.com/file/2023/5/84895_0s.png)
Python爬取视频时长场景实践示例
![](https://img.aspxhome.com/file/2023/9/65139_0s.png)
在Pytorch中使用Mask R-CNN进行实例分割操作
![](https://img.aspxhome.com/file/2023/1/79571_0s.jpg)
Python 16进制与中文相互转换的实现方法
基于python分享一款地理数据可视化神器keplergl
![](https://img.aspxhome.com/file/2023/2/95432_0s.gif)