分享提高 Python 代码的可读性的技巧


Posted in Python onMarch 03, 2022

1. 字符串反转

字符串反转有很多方法,咱们再这里介绍两种:一种是切片,一种是python字符串的reversed方法。

# -!- coding: utf-8 -!-
string = 'hello world'

# 方法1
new_str = string[::-1]
ic(new_str)

# 方法二
new_str2 = ''.join(reversed(string))
ic(new_str2)

'''
ic| new_str: 'dlrow olleh'
ic| new_str2: 'dlrow olleh'
'''

2. 首字母大写

这里咱们也是介绍两种方法,区别之处在于**capitalize()**仅是首字母大写

**title()**是每个单词开头的首字母都大写

# 首字母大写
string = 'hello python and world'

# 方法一
new_str = string.capitalize()
ic(new_str)


# 方法二
new_str2 = string.title()
ic(new_str2)

'''
ic| new_str: 'Hello python and world'
ic| new_str2: 'Hello Python And World'
'''

3. 查询唯一元素

我们利用set的唯一性来确定字符串的唯一元素:

string = 'hellohellohello'
new_str = set(string)
# set类型
ic(new_str)
# 字符串类型
new_str = ''.join(new_str)
ic(new_str)

'''
ic| new_str: {'l', 'o', 'h', 'e'}
ic| new_str: 'lohe'
'''

4. 变量交换

python中的变量交换比java简单多了,交换两个变量无需定义第三个中间变量,直接交换即可实现

a = 'hello'
b = 'world'
ic(a+b)

# 直接交换两个变量
a, b = b, a
ic(a+b)

'''
ic| a+b: 'helloworld'
ic| a+b: 'worldhello'
'''

5. 列表排序

列表排序这里我们也提供两种方式。第一个是列表自带的**sort()方法;第二个是python内置函数sorted()**方法

score = [88, 99, 91, 85, 94, 85, 94, 78, 100, 80]
# 方法一
new_score = sorted(score)
ic('默认升序:', new_score)

score = [57, 29, 11, 27, 84, 34, 87, 25, 70, 60]
# 方法二
new_score2 = sorted(score, reverse=True)
ic('设置降序', new_score2)

'''
ic| '默认升序:', new_score: [78, 80, 85, 85, 88, 91, 94, 94, 99, 100]
ic| '设置降序', new_score2: [87, 84, 70, 60, 57, 34, 29, 27, 25, 11]
'''

6.列表推导式

使用列表推导式可以快速生成一个列表或者根据列表生成满足需求的列表

# 生成10个10-100以内随机整数
numbers = [random.randint(10, 100) for x in range(10)]
ic(numbers)

# 输入5折后的价格
price = [800, 500, 400, 860, 780, 520, 560]
half_price = [(x*0.5)for x in price]
ic(half_price)

'''
ic| numbers: [64, 22, 80, 70, 34, 81, 74, 35, 85, 12]
ic| half_price: [400.0, 250.0, 200.0, 430.0, 390.0, 260.0, 280.0]
'''

7. 合并字符串

合并字符串我们使用string.join()方法实现

lists = ['hello', 'world', 'python', 'java', 'c++']

# 合并字符串
new_str = ' '.join(lists)
ic(new_str)

'''
ic| new_str: 'hello world python java c++'
'''

8. 拆分字符串

拆分字符串我们使用string的split()方法实现

string = 'hello world python java c++'
string2 = 'hello|world|python|java|c++'

# 拆分字符串
new_str = string.split(' ')
ic(new_str)

new_str2 = string2.split('|')
ic(new_str2)

'''
ic| new_str: ['hello', 'world', 'python', 'java', 'c++']
ic| new_str2: ['hello', 'world', 'python', 'java', 'c++']
'''

9. 回文串检测

回文串是指abaabbacccbcccaaaa这种左右对称的字符串。我们可以根据之前提到的切片来检测这种特殊的字符串序列

str = '20211202'

if str == str[::-1]:
    print('yes')
else:
    print('no')

'''
yes
'''

10. 统计列表元素出现次数

统计列表中元素各自出现的次数我们使用collections Counter方法

from collections import Counter
lists = ['a', 'a', 'b', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd']

# 统计所有元素出现的次数
counts = Counter(lists)
ic(counts)

# 统计某一元素出现的次数
ic(counts['d'])

# 统计出现最多次数的一个元素
ic(counts.most_common(1))

'''
ic| counts: Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
ic| counts['d']: 5
ic| counts.most_common(1): [('d', 5)]
'''

到此这篇关于分享10提高 Python 代码的可读性的技巧的文章就介绍到这了,更多相关提高 Python 代码可读性内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
让python的Cookie.py模块支持冒号做key的方法
Dec 28 Python
Python原始字符串与Unicode字符串操作符用法实例分析
Jul 22 Python
Python下载网络文本数据到本地内存的四种实现方法示例
Feb 05 Python
Python 中的range(),以及列表切片方法
Jul 02 Python
python实现自动登录后台管理系统
Oct 18 Python
Python 存储字符串时节省空间的方法
Apr 23 Python
Python实现平行坐标图的绘制(plotly)方式
Nov 22 Python
python GUI库图形界面开发之PyQt5下拉列表框控件QComboBox详细使用方法与实例
Feb 27 Python
Python键鼠操作自动化库PyAutoGUI简介(小结)
May 17 Python
python的数学算法函数及公式用法
Nov 18 Python
python 如何用urllib与服务端交互(发送和接收数据)
Mar 04 Python
python 详解turtle画爱心代码
Feb 15 Python
使用python创建股票的时间序列可视化分析
Python Pandas读取Excel日期数据的异常处理方法
pytorch中的torch.nn.Conv2d()函数图文详解
Feb 28 #Python
python3中apply函数和lambda函数的使用详解
Feb 28 #Python
你需要掌握的20个Python常用技巧
Feb 28 #Python
python opencv将多个图放在一个窗口的实例详解
pandas中关于apply+lambda的应用
Feb 28 #Python
You might like
创建配置文件 用PHP写出自己的BLOG系统 2
2010/04/12 PHP
关于初学PHP时的知识积累总结
2013/06/07 PHP
php递归使用示例(php递归函数)
2014/02/14 PHP
PHP调用wsdl文件类型的接口代码分享
2014/11/19 PHP
Yii的CDbCriteria查询条件用法实例
2014/12/04 PHP
Codeigniter控制器controller继承问题实例分析
2016/01/19 PHP
joomla组件开发入门教程
2016/05/04 PHP
深入学习微信网址链接解封的防封原理visit_type
2019/08/15 PHP
jquery 表单取值常用代码
2009/12/22 Javascript
Extjs中ComboBox加载并赋初值的实现方法
2012/03/22 Javascript
JavaScript中的类数组对象介绍
2014/12/30 Javascript
js实现可旋转的立方体模型
2016/10/16 Javascript
利用VUE框架,实现列表分页功能示例代码
2017/01/12 Javascript
JavaScript模拟文件拖选框样式v1.0的实例
2017/08/04 Javascript
Vuejs 2.0 子组件访问/调用父组件的方法(示例代码)
2018/02/08 Javascript
vue全局自定义指令-元素拖拽的实现代码
2019/04/14 Javascript
浅谈Vuex注入Vue生命周期的过程
2019/05/20 Javascript
JS多个表单数据提交下的serialize()应用实例分析
2019/08/27 Javascript
js实现开关灯效果
2020/03/30 Javascript
vue.js实现二级菜单效果
2019/10/19 Javascript
js实现移动端轮播图滑动切换
2020/12/21 Javascript
[01:02:25]2014 DOTA2华西杯精英邀请赛5 24 NewBee VS VG
2014/05/25 DOTA
详解Python locals()的陷阱
2019/03/26 Python
Python3 全自动更新已安装的模块实现
2020/01/06 Python
Python Numpy库常见用法入门教程
2020/01/16 Python
jupyter notebook 添加kernel permission denied的操作
2020/04/21 Python
torchxrayvision包安装过程(附pytorch1.6cpu版安装)
2020/08/26 Python
HTML5之SVG 2D入门5—颜色的表示及定义方式
2013/01/30 HTML / CSS
Diamondback自行车:拥有你的冒险
2019/04/22 全球购物
EJB的基本架构
2016/09/22 面试题
2014年大学庆元旦迎新年活动方案
2014/03/09 职场文书
经典促销广告词大全
2014/03/19 职场文书
工作批评与自我批评范文
2014/10/16 职场文书
2014年小学德育工作总结
2014/12/05 职场文书
2015年安置帮教工作总结
2015/05/22 职场文书
django 认证类配置实现
2021/11/11 Python