分享提高 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操作json数据的一个简单例子
Apr 17 Python
python实现爬虫统计学校BBS男女比例之多线程爬虫(二)
Dec 31 Python
Python计算两个日期相差天数的方法示例
May 23 Python
CentOS 6.5下安装Python 3.5.2(与Python2并存)
Jun 05 Python
Python使用回溯法子集树模板解决迷宫问题示例
Sep 01 Python
用tensorflow构建线性回归模型的示例代码
Mar 05 Python
Python-OpenCV基本操作方法详解
Apr 02 Python
Python lxml解析HTML并用xpath获取元素的方法
Jan 02 Python
深入解析Python小白学习【操作列表】
Mar 23 Python
关于TensorFlow新旧版本函数接口变化详解
Feb 10 Python
python中的错误如何查看
Jul 08 Python
基于tensorflow __init__、build 和call的使用小结
Feb 26 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
ThinkPHP视图查询详解
2014/06/30 PHP
PHP数组相加操作及与array_merge的区别浅析
2016/11/26 PHP
thinkphp中U方法按路由规则生成url的方法
2018/03/12 PHP
JS Timing
2007/04/21 Javascript
JQuery EasyUI 日期控件如何控制日期选择区间
2014/05/05 Javascript
Jquery方式获取iframe页面中的 Dom元素
2014/05/07 Javascript
Javascript中的delete操作符详细介绍
2014/06/06 Javascript
javascript模拟post提交隐藏地址栏的参数
2014/09/03 Javascript
javascript:void(0)是什么意思及href=#与href=javascriptvoid(0)的区别
2015/11/13 Javascript
理解Angular数据双向绑定
2016/01/10 Javascript
JS实现的自定义水平滚动字体插件完整实例
2016/06/17 Javascript
vue实现可增删查改的成绩单
2016/10/27 Javascript
详解Vue自定义过滤器的实现
2017/01/10 Javascript
H5实现中奖记录逐行滚动切换效果
2017/03/13 Javascript
使用Vue做一个简单的todo应用的三种方式的示例代码
2018/10/20 Javascript
Vue 理解之白话 getter/setter详解
2019/04/16 Javascript
使用express获取微信小程序二维码小记
2019/05/21 Javascript
微信小程序开发注意指南和优化实践(小结)
2019/06/21 Javascript
mui js控制开关状态、修改switch开关的值方法
2019/09/03 Javascript
[04:49]期待西雅图之战 2016国际邀请赛中国区预选赛WINGS战队赛后采访
2016/06/29 DOTA
[02:38]DOTA2亚洲邀请赛小组赛精彩集锦:Wings完美团击溃对手
2017/03/29 DOTA
Python中atexit模块的基本使用示例
2015/07/08 Python
使用python3.5仿微软记事本notepad
2016/06/15 Python
python3.x实现发送邮件功能
2018/05/22 Python
浅谈python脚本设置运行参数的方法
2018/12/03 Python
Python使用Turtle库绘制一棵西兰花
2019/11/23 Python
简单了解Django ORM常用字段类型及参数配置
2020/01/07 Python
python脚本定时发送邮件
2020/12/22 Python
服装公司总经理岗位职责
2013/11/30 职场文书
初中生自我鉴定
2014/02/04 职场文书
考察邀请函范文
2015/01/31 职场文书
2015年社区平安建设工作总结
2015/05/13 职场文书
在职证明范本
2015/06/15 职场文书
在校学生证明格式
2015/06/24 职场文书
导游词之湖北梁子湖
2019/11/07 职场文书
JavaScript中MutationObServer监听DOM元素详情
2021/11/27 Javascript