分享提高 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中的filter和lambda函数的使用
Apr 07 Python
Python操作Word批量生成文章的方法
Jul 28 Python
Python用模块pytz来转换时区
Aug 19 Python
Python进程间通信之共享内存详解
Oct 30 Python
使用python脚本实现查询火车票工具
Jul 19 Python
对python PLT中的image和skimage处理图片方法详解
Jan 10 Python
深入解析Python小白学习【操作列表】
Mar 23 Python
Python3 Tkinter选择路径功能的实现方法
Jun 14 Python
Python使用__new__()方法为对象分配内存及返回对象的引用示例
Sep 20 Python
给大家整理了19个pythonic的编程习惯(小结)
Sep 25 Python
Python插件机制实现详解
May 04 Python
django上传文件的三种方式
Apr 29 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中的多态性[译]
2011/08/02 PHP
php禁用函数设置及查看方法详解
2016/07/25 PHP
jquery 输入框数字限制插件
2009/11/10 Javascript
最新28个很棒的jQuery 教程
2011/05/28 Javascript
jquery可见性过滤选择器使用示例
2013/06/24 Javascript
jquery教程限制文本框只能输入数字和小数点示例分享
2014/01/13 Javascript
JQuery EasyUI 加载两次url的原因分析及解决方案
2014/08/18 Javascript
jQuery实现复选框成对选择及对应取消的方法
2015/03/03 Javascript
面向切面编程(AOP)的理解
2015/05/01 Javascript
javascript实现简易计算器的代码
2016/05/31 Javascript
JS生成一维码(条形码)功能示例
2017/01/19 Javascript
js遮罩效果制作弹出注册界面效果
2017/01/25 Javascript
js设置鼠标悬停改变背景色实现详解
2019/06/26 Javascript
vue router总结 $router和$route及router与 router与route区别
2019/07/05 Javascript
Vue通过for循环随机生成不同的颜色或随机数的实例
2019/11/09 Javascript
Vue实现验证码功能
2019/12/03 Javascript
《javascript设计模式》学习笔记一:Javascript面向对象程序设计对象成员的定义分析
2020/04/07 Javascript
[01:58]2018DOTA2亚洲邀请赛趣味视频——交流
2018/04/03 DOTA
让python的Cookie.py模块支持冒号做key的方法
2010/12/28 Python
简单的Apache+FastCGI+Django配置指南
2015/07/22 Python
实例Python处理XML文件的方法
2015/08/31 Python
Python实现优先级队列结构的方法详解
2016/06/02 Python
Python实现简单的获取图片爬虫功能示例
2017/07/12 Python
python实现复制大量文件功能
2019/08/31 Python
Pytorch实现基于CharRNN的文本分类与生成示例
2020/01/08 Python
CSS3 border-image详解、应用及jQuery插件
2011/08/29 HTML / CSS
美国花布包包品牌:Vera Bradley
2017/08/11 全球购物
德国运动鞋网上商店:Afew Store
2018/01/05 全球购物
掌上明珠Java程序员面试总结
2016/02/23 面试题
求职信模版
2013/11/30 职场文书
股份合作协议书
2014/04/12 职场文书
个人担保书范文
2014/05/20 职场文书
党员民主生活会材料
2014/12/15 职场文书
2017年寒假少先队活动总结
2016/04/06 职场文书
python opencv将多个图放在一个窗口的实例详解
2022/02/28 Python
3050和2060哪个好 性能差多少 差距有多大 谁更有性价比
2022/06/17 数码科技