分享提高 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 MySQLdb Linux下安装笔记
May 09 Python
Python数据分析之如何利用pandas查询数据示例代码
Sep 01 Python
Python竟能画这么漂亮的花,帅呆了(代码分享)
Nov 15 Python
Python语言描述随机梯度下降法
Jan 04 Python
Python logging管理不同级别log打印和存储实例
Jan 19 Python
pandas.loc 选取指定列进行操作的实例
May 18 Python
使用python判断jpeg图片的完整性实例
Jun 10 Python
python函数的万能参数传参详解
Jul 26 Python
python爬虫增加访问量的方法
Aug 22 Python
Python用requests库爬取返回为空的解决办法
Feb 21 Python
如何利用python和DOS获取wifi密码
Mar 31 Python
在python中读取和写入CSV文件详情
Jun 28 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
Win9x/ME下Apache+PHP安装配置
2006/10/09 PHP
php 购物车的例子
2009/05/04 PHP
PHP通用检测函数集合
2011/02/08 PHP
PHP将两个关联数组合并函数提高函数效率
2014/03/18 PHP
php可生成缩略图的文件上传类实例
2014/12/17 PHP
php实现多城市切换特效
2015/08/09 PHP
学习PHP Cookie处理函数
2016/08/09 PHP
脚本之家贴图转换+转贴工具用到的js代码超级推荐
2007/04/05 Javascript
多浏览器兼容性比较好的复制到剪贴板的js代码
2011/10/09 Javascript
获取客户端网卡MAC地址和IP地址实现JS代码
2013/03/17 Javascript
用javascript将数据导入Excel示例代码
2014/09/10 Javascript
node.js中的path.dirname方法使用说明
2014/12/09 Javascript
js获取会话框prompt的返回值的方法
2015/01/10 Javascript
Webpack中publicPath路径问题详解
2018/05/03 Javascript
vue实现Input输入框模糊查询方法
2021/01/29 Javascript
python的tkinter布局之简单的聊天窗口实现方法
2014/09/03 Python
python通过pil模块将raw图片转换成png图片的方法
2015/03/16 Python
python中使用xlrd读excel使用xlwt写excel的实例代码
2018/01/31 Python
基于python的图片修复程序(实现水印去除)
2018/06/04 Python
pytorch 转换矩阵的维数位置方法
2018/12/08 Python
python实现windows壁纸定期更换功能
2019/01/21 Python
Numpy数组array和矩阵matrix转换方法
2019/08/05 Python
html5使用window.postMessage进行跨域实现数据交互的一次实战
2021/02/24 HTML / CSS
澳大利亚足球鞋和服装购物网站:Ultra Football
2018/10/11 全球购物
西雅图电动自行车公司:Rad Power Bikes
2020/02/02 全球购物
C语言编程题
2015/03/09 面试题
电信营业员自我评价分享
2014/01/17 职场文书
工程项目建议书范文
2014/03/12 职场文书
自行车广告词大全
2014/03/21 职场文书
班长演讲稿范文
2014/04/24 职场文书
房屋产权共有协议书范本
2014/11/03 职场文书
2015年感恩父亲节演讲稿
2015/03/19 职场文书
保险公司客户经理岗位职责
2015/04/09 职场文书
英语专业毕业论文答辩开场白
2015/05/27 职场文书
spring IOC容器的Bean管理XML自动装配过程
2022/05/30 Java/Android
SQLServer常见数学函数梳理总结
2022/08/05 MySQL