分享提高 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的三目运算符和not in运算符使用示例
Mar 03 Python
Python中logging模块的用法实例
Sep 29 Python
python处理大数字的方法
May 27 Python
python利用正则表达式排除集合中字符的功能示例
Oct 10 Python
在Python中分别打印列表中的每一个元素方法
Nov 07 Python
Python StringIO如何在内存中读写str
Jan 07 Python
从0到1使用python开发一个半自动答题小程序的实现
May 12 Python
keras模型保存为tensorflow的二进制模型方式
May 25 Python
pytorch 限制GPU使用效率详解(计算效率)
Jun 27 Python
django template实现定义临时变量,自定义赋值、自增实例
Jul 12 Python
基于Python 函数和方法的区别说明
Mar 24 Python
Django模型层实现多表关系创建和多表操作
Jul 21 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
19个超实用的PHP代码片段
2014/03/14 PHP
PHP错误Parse error: syntax error, unexpected end of file in test.php on line 12解决方法
2014/06/23 PHP
PHP中Memcache操作类及用法实例
2014/12/12 PHP
yii2项目实战之restful api授权验证详解
2017/05/20 PHP
PHP多进程编程之僵尸进程问题的理解
2017/10/15 PHP
符合标准的js表单提交的代码
2007/09/13 Javascript
JS实现self的resend
2010/07/22 Javascript
file模式访问网页时iframe高度自适应解决方案
2013/01/16 Javascript
jquery 获取 outerHtml 包含当前节点本身的代码
2014/10/30 Javascript
Javascript基础教程之定义和调用函数
2015/01/18 Javascript
jquery实现select下拉框美化特效代码分享
2015/08/18 Javascript
JS实现的自定义水平滚动字体插件完整实例
2016/06/17 Javascript
Javascript点击按钮随机改变数字与其颜色
2016/09/01 Javascript
jQuery滚动插件scrollable.js用法分析
2017/05/25 jQuery
jquery实现放大镜简洁代码(推荐)
2017/06/08 jQuery
Layui Table js 模拟选中checkbox的例子
2019/09/03 Javascript
JavaScript生成一个不重复的ID的方法示例
2019/09/16 Javascript
关于uniApp editor微信滑动问题
2021/01/15 Javascript
python中使用OpenCV进行人脸检测的例子
2014/04/18 Python
python编程通过蒙特卡洛法计算定积分详解
2017/12/13 Python
python 将字符串转换成字典dict的各种方式总结
2018/03/23 Python
python实现抽奖小程序
2020/04/15 Python
用python3读取python2的pickle数据方式
2019/12/25 Python
tensorflow 模型权重导出实例
2020/01/24 Python
python MultipartEncoder传输zip文件实例
2020/04/07 Python
Python 实现图片转字符画的示例(静态图片,gif皆可)
2020/11/05 Python
Python json解析库jsonpath原理及使用示例
2020/11/25 Python
Html5实现单张、多张图片上传功能
2019/04/28 HTML / CSS
日本最新流行服饰网购:Nissen
2016/07/24 全球购物
Move Free官方海外旗舰店:美国骨关节健康专业品牌
2017/12/06 全球购物
日本高岛屋百货购物网站:TAKASHIMAYA
2019/03/24 全球购物
员工拓展培训方案
2014/02/15 职场文书
超市七夕促销活动方案
2014/08/28 职场文书
股东合作协议书
2014/09/12 职场文书
招商银行工作证明
2015/06/17 职场文书
关于mysql中时间日期类型和字符串类型的选择
2021/11/27 MySQL