【Python Cookbook】S1E09 对切片命名

目录

问题

代码的可阅读性非常重要,如何增强切片中的可阅读性?本文将提供一种方案。

解决方案

假设有一些代码用来从字符串的固定位置取出具体的数据:

python 复制代码
record = "...100...513.25..."
cost = int(record[3:6]) * float(record[9:15])
print("cost is ", cost)

上述的代码可读性和可维护性很低,在一段时间后再回看这段代码,可能会发现自己都难理解这两个字段到底是什么。对于这种切片切分,不妨我们使用合理的命名,不仅便于后期维护,还可显著增加代码的可阅读性:

python 复制代码
shares = slice(3, 6)
price = slice(9, 15)
cost = int(record[shares]) * float(record[price])
print("cost is ", cost)

讨论

slice() 函数,不仅可以用于上述增强代码的可阅读性,其本质上会创建一个切片对象,我们可以在对象的实例上进行很多其他的操作。

假设有一个 slice 对象的实例 s ,我们可以分别通过 s.starts.stop 以及 s.step 属性来得到关于该对象的信息,例如:

python 复制代码
s = slice(3, 6, 2)
print("s.start =", s.start)
print("s.stop = ", s.stop)
print("s.step = ", s.step)

所以可以看出,slice 对象有三个参数,分别是 (start, stop, step) ,顾名思义,即开始的 index ,结束的 index 以及每一步的跨步大小是多少 step

相关推荐
孤狼warrior16 分钟前
灰色预测模型
人工智能·python·算法·数学建模
神仙别闹21 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金1 小时前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP1 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
zdw2 小时前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python
剑桥折刀s2 小时前
Python打卡:Day46
python
巴里巴气3 小时前
Python爬虫图片验证码和滑块验证码识别总结
爬虫·python
sword devil9003 小时前
PYQT实战:智能家居中控
python·智能家居·pyqt