分享提高 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 相关文章推荐
pyqt4教程之messagebox使用示例分享
Mar 07 Python
python开发之for循环操作实例详解
Nov 12 Python
Python学习小技巧之利用字典的默认行为
May 20 Python
pandas数据分组和聚合操作方法
Apr 11 Python
在scrapy中使用phantomJS实现异步爬取的方法
Dec 17 Python
python 实现一次性在文件中写入多行的方法
Jan 28 Python
Python合并同一个文件夹下所有PDF文件的方法
Mar 11 Python
Python PIL读取的图像发生自动旋转的实现方法
Jul 05 Python
django商品分类及商品数据建模实例详解
Jan 03 Python
Python&&GDAL实现NDVI的计算方式
Jan 09 Python
python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例
Mar 10 Python
Python键鼠操作自动化库PyAutoGUI简介(小结)
May 17 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+js iframe实现上传头像界面无跳转
2014/04/29 PHP
YII中assets的使用示例
2014/07/31 PHP
PHP入门教程之字符串处理技巧总结(转换,过滤,解析,查找,截取,替换等)
2016/09/11 PHP
10个值得深思的PHP面试题
2016/11/14 PHP
网页javascript精华代码集
2007/01/24 Javascript
使用jQuery UI的tooltip函数修饰title属性的气泡悬浮框
2013/06/24 Javascript
jquery实现人性化的有选择性禁用鼠标右键
2014/06/30 Javascript
javascript实现分栏显示小技巧附图
2014/10/13 Javascript
jQuery中prevAll()方法用法实例
2015/01/08 Javascript
jQuery弹出层插件Lightbox_me使用指南
2015/04/21 Javascript
在AngularJS中如何使用谷歌地图把当前位置显示出来
2016/01/25 Javascript
AngularJS中如何使用$parse或$eval在运行时对Scope变量赋值
2016/01/25 Javascript
使用JavaScript判断手机浏览器是横屏还是竖屏问题
2016/08/02 Javascript
JS关闭窗口时产生的事件及用法示例
2016/08/20 Javascript
jquery.validate[.unobtrusive]和Bootstrap实现tooltip错误提示问题分析
2016/10/30 Javascript
vue2 中如何实现动态表单增删改查实例
2017/06/09 Javascript
在Swiper内如何制作CSS3动画效果示例代码
2017/12/07 Javascript
解决vue-cli脚手架打包后vendor文件过大的问题
2018/09/27 Javascript
微信小程序云函数添加数据到数据库的方法
2020/03/04 Javascript
[05:59]2018DOTA2国际邀请赛寻真——只为胜利的Secret
2018/08/13 DOTA
python 判断自定义对象类型
2009/03/21 Python
python 实现归并排序算法
2012/06/05 Python
Python中的choice()方法使用详解
2015/05/15 Python
python实现飞机大战游戏
2020/10/26 Python
python实现将文件夹内的每张图片批量分割成多张
2019/07/22 Python
Canvas 文字碰撞检测并抽稀的方法
2019/05/27 HTML / CSS
html5 canvas 实现光线沿不规则路径运动
2020/04/20 HTML / CSS
丝芙兰美国官网:SEPHORA美国
2016/08/03 全球购物
《油菜花开了》教学反思
2014/02/22 职场文书
工商企业管理专业自荐信范文
2014/04/12 职场文书
党风廉设责任书
2014/04/16 职场文书
电子商务系毕业生自荐信
2014/05/29 职场文书
五四演讲稿范文
2014/09/03 职场文书
2016年小学生迎国庆广播稿
2015/12/18 职场文书
公开致歉信
2019/06/24 职场文书
晶体管单管来复再生式收音机
2021/04/22 无线电