如何让你的python代码简洁优雅
1、多变量赋值
name1 = 'Ray',
name2 = 'Mary',
name3 = 'Jacky'
优化写法:
直接按顺序对应一一赋值
name1, name2, name3 = 'Ray', 'Mary', 'Jacky'
运行结果:
In [1]: name1, name2, name3 = 'Ray', 'Mary', 'Jacky'
In [2]: print(name1)
Ray
In [3]: print(name2)
Mary
In [4]: print(name3)
Jacky
2、判断语句优化
index = 3
if index < 3:
index = -index
else:
index = 3
优化写法:
使用python中的三目运算符
# 简写方式(相当于其他语言中的三目运算符)
num = -index if index < 3 else 3
运行结果:
In [10]: num = -index if index < 3 else 3
In [11]: print(num)
3
3、多重条件条件区间优化
3.1 短路与(and)
age = 25
if age >=18 and age < 35:
print("Congratulations on meeting our recruitment requirements!")
优化写法:
使用链式判断
age = 25
# 注意这种写法在强类型的语言中或许不适用,在python中是可行的
if 18 <= age < 35:
print("Congratulations on meeting our recruitment requirements!")
运行结果:
In [18]: age = 25
In [19]: if 18 <= age < 35:
...: print("Congratulations on meeting our recruitment requirements!")
...:
Congratulations on meeting our recruitment requirements!
In [20]:
3.2 短路或(or)
age = 25
if age ==18 or age = 25 or age = 30:
print("Congratulations on meeting our recruitment requirements!")
优化写法:
使用关键字in
age = 25
# 注意这种写法在强类型的语言中或许不适用,在python中是可行的
if age in (18, 25, 30):
print("Congratulations on meeting our recruitment requirements!")
运行结果:
In [21]: age = 25
In [22]: if age in (18, 25, 30):
...: print("Congratulations on meeting our recruitment requirements!")
...:
Congratulations on meeting our recruitment requirements!
In [23]:
4、序列解包
stu_info = ['qingchen', 18, 'student']
name = stu_info[0]
age = stu_info[1]
profession = stu_info[2]
print(name,age, profession)
优化写法:
给出对应变量元组接收列表所有元素
stu_info = ['qingchen', 18, 'student']
name, age, profession = stu_info
print(name,age, profession)
运行结果:
In [28]: stu_info = ['qingchen', 18, 'student']
In [29]: name, age, profession = stu_info
In [30]: print(name, age, profession)
qingchen 18 student
In [31]:
5、空数据判断
# 通常我们对数据为空的判断都是看数据的长度是否为0,如下示例
list_demo, dirc_demo, str_demo = [1, 3, 5, 7, 9], {}, ""
if len(list_demo) > 0:
print('list_demo 为非空')
if len( dirc_demo) > 0:
print('dirc_demo 为非空')
if len(str_demo ) > 0:
print('str_demo 为非空')
优化写法:
if 后面的执行条件是可以简写的,只要条件 是非零数值、非空字符串、非空 list 等,就判断为 True,否则为 False。
list_demo, dirc_demo, str_demo = [1, 3, 5, 7, 9], {}, ""
if list_demo:
print('list_demo 为非空')
if dirc_demo:
print('dirc_demo 为非空')
if str_demo:
print('str_demo 为非空')
运行结果:
In [32]: list_demo, dirc_demo, str_demo = [1, 3, 5, 7, 9], {}, ""
In [33]: if list_demo:
...: print("list_demo 非空")
...: if dirc_demo:
...: pritn("dirc_demo 非空")
...: if str_demo:
...: print("str_demo 为非空")
...:
list_demo 非空
6、多条件内容判断
6.1 多条件内容判断至少一个成立
math, English, chinese = 85, 90, 58
if math < 60 or English < 60 or chinese < 60:
print('failed')
# 结果
failed
优化写法:
使用any语句
math, English, chinese = 85, 90, 58
if any([math < 60, English < 60, chinese < 60]):
print('failed')
运行结果:
In [37]: math, English, chinese = 85, 90, 58
In [38]: if any([math < 60, English < 60, chinese < 60]):
...: print( 'failed')
failed
6.2 多条件内容判断全部成立
math, English, chinese = 85, 90, 75
if math > 60 or English > 60 or chinese > 60:
print('passed')
# 结果
failed
优化写法:
使用all语句
math, English, chinese = 85, 90, 75
if all([math > 60, English > 60, chinese > 60]):
print('passed')
运行结果:
In [37]: math, English, chinese = 85, 90, 75
In [38]: if all([math > 60, English > 60, chinese > 60]):
...: print( 'passed')
...:
passed
7、遍历list的元素和元素索引
# 通常都使用 for 循环进行遍历元素和下标
L =['math', 'English', 'computer', 'Physics']
for i in range(len(L)):
print(i, ':', L[i])
# 结果
0 : math
1 : English
2 : computer
3 : Physics
优化写法:
使用enumerate 函数
L =['math', 'English', 'computer', 'Physics']
for k,v in enumerate(L):
print(k, ':', v)
运行结果:
In [44]: L =['math', 'English', 'computer', 'Physics']
In [45]: for k,v in enumerate(L):
...: print(k, ':', v)
...:
0 : math
1 : English
2 : computer
3 : Physics
In [46]:
7、循环语句优化
# 通常都使用 for 循环进行遍历元素和下标
list_demo = []
for i in range(1, 6):
list_demo .append(i*i)
print(list_demo )
#结果:
[1, 4, 9, 16, 25]
优化写法:
使用列表生成式
print([x**2 for x in range(1,6)])
运行结果:
In [47]: print([x**2 for x in range(1,6)])
[1, 4, 9, 16, 25]
In [48]:
文章最后推荐给大家一个学习优化python代码的好的博文,请大家自己去学习,祝大家每天都能避昨天进步!
https://blog.youkuaiyun.com/github_36326955/article/details/71330217