详解python编程slice与indices函数用法示例
作者:沉沉沉小姐 时间:2021-03-23 05:13:22
一般来说,内置的slice()函数会创建一个切片对象,可以用在任何允许进行切片操作的地方。
下面是slice的简介:
# slice 两种用法
class slice(stop)
class slice(start, stop[, step])
返回一个表示由 range(start, stop, step)
所指定索引集的 slice 对象。 其中 start 和 step 参数默认为 None
。 切片对象具有仅会返回对应参数值(或其默认值)的只读数据属性 start
, stop
和 step
。 它们没有其他的显式功能;不过它们会被 NumPy 以及其他第三方扩展所使用。
切片对象也会在使用扩展索引语法时被生成。 例如: a[start:stop:step]
或 a[start:stop, i]
。
请参阅 itertools.islice() 了解返回迭代器的一种替代版本。
items = [0, 1, 2, 3, 4, 5, 6]
a = slice(2,4)
print(items[2:4])
# [2, 3]
items[a]
# [2:3]
items[a] = [10, 11]
print(items)
# [0, 1, 10, 11, 4, 5, 6]
del items[a]
# [0, 1, 4, 5, 6]
如果有一个slice对象的实例s,可以分别通过s.atart、s.stop以及s.step属性来得到关于该对象的信息。例:
a = slice(10, 50, 2)
print(a.start)
# 10
print(a.stop)
# 50
print(a.step)
# 2
下面是indices官方解释:
slice.
indices
(self, length)
此方法接受一个整型参数 length 并计算在切片对象被应用到 length 指定长度的条目序列时切片的相关信息应如何描述。其返回值为三个整型数组成的元组;这些数分别为切片的 start 和 stop 索引号以及 step 步长值。索引号缺失或越界则按照正规连续切片的方式处理。
所有的值都已经恰当的限制在边界以内(当做索引操作时可避免出现IndexError异常)例:
s = 'HelloWorld'a.indices(len(s))# (5, 10, 2)for i in range (*a.indices(len(s))): print(s[i])# w# r# d
来源:https://blog.csdn.net/chenyuhuaxin/article/details/100565816
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用tensorflow实现AlexNet
![](https://img.aspxhome.com/file/2023/0/62310_0s.jpg)
Flask框架web开发之零基础入门
![](https://img.aspxhome.com/file/2023/4/83944_0s.png)
Python操作JSON实现网络数据交换
Python如何使用pymongo连接MongoDB数据库并进行相关操作
![](https://img.aspxhome.com/file/2023/7/72017_0s.png)
用python实现五子棋实例
![](https://img.aspxhome.com/file/2023/8/65908_0s.jpg)
Oracle数据库系统紧急故障处理方法
Django form表单与请求的生命周期步骤详解
从算法入手讲解SQL Server的典型示例
解决python3 网络请求路径包含中文的问题
Python中fnmatch模块的使用详情
利用golang的字符串解决leetcode翻转字符串里的单词
![](https://img.aspxhome.com/file/2023/8/99048_0s.jpg)
CSS中的标点符号用法
你会使用python爬虫抓取弹幕吗
![](https://img.aspxhome.com/file/2023/9/77659_0s.png)
GO语言操作Elasticsearch示例分享
Tensorflow 多线程设置方式
php curl登陆qq后获取用户信息时证书错误
Python使用tkinter实现小时钟效果
![](https://img.aspxhome.com/file/2023/8/68888_0s.jpg)