python优雅写法

Python 的设计哲学是「优雅」、「明确」、「简单」,

一. 为多个变量赋值

# 常规写法
a = 0
b = 1
c = 2
# 优雅写法,按顺序一一赋值
a, b, c = 0, 1, 2

二. 为多个变量赋值

# 常规写法
info = ['brucepk', 'man', 'python']
name = info[0]
sex = info[1]
tech = info[2]
print(name,sex,tech)

# 结果
brucepk man python
# 优雅写法
info = ['brucepk', 'man', 'python']
name,sex,tech = info
print(name,sex,tech)

# 结果
brucepk man python

三. 判断语句

# 常规写法
x = -6
if x < 0:
    y = -x
else:
    y = x
print(y)

# 结果
6
# 优雅写法
x = -6
y = -x if x<0 else x
print(y)

# 结果
6

四. 区间判断

# 常规写法
score = 82
if score >=80 and score < 90:
    level = 'B'
print(level)

# 结果
B
# 优雅写法,使用链式判断。
score = 82
if  80 <= score < 90:
    level = 'B'
print(level)

# 结果
B

五. 多个值符合条件判断

# 常规写法
num = 1
if num == 1 or num == 3 or num == 5:
    type = '奇数'
print(type)

# 结果
奇数
#优雅写法,使用关键字 in,让你的语句更优雅。
num = 1
if num in(1,3,5):
    type = '奇数'
print(type)

# 结果
奇数

六. 判断是否为空

# 常规写法
A,B,C =[1,3,5],{},''
if len(A) > 0:
    print('A 为非空')
if len(B) > 0:
    print('B 为非空')
if len(C) > 0:
    print('C 为非空')

# 结果
A 为非空
# 优雅写法
A,B,C =[1,3,5],{},''
if A:
    print('A 为非空')
if B:
    print('B 为非空')
if C:
    print('C 为非空')

# 结果
A 为非空

七. 多条件内容判断至少一个成立

# 常规写法,用 or 连接多个条件。
math,English,computer =90,80,88
if math<60 or English<60 or computer<60:
    print('not pass')

# 结果
not pass
# 优雅写法,使用 any 语句。

math,English,computer =90,59,88
if any([math<60,English<60,computer<60]):
    print('not pass')

# 结果
not pass

八. 多条件内容判断全部成立

# 常规方法,使用 and 连接条件做判断。
math,English,computer =90,80,88
if math>60 and English>60 and computer>60:
    print('pass')

# 结果
pass
# 优雅方法,使用 all 方法。
math,English,computer =90,80,88
if all([math>60,English>60,computer>60]):
    print('pass')

# 结果
pass

九. 遍历序列的元素和元素下标

# 常规方法,使用 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)

# 结果
0 : math
1 : English
2 : computer
3 : Physics

十. 循环语句优化

# 常规方法
L = []
for i in range(1, 6):
    L.append(i*i)
print(L) 

#结果:
[1, 4, 9, 16, 25]
# 优雅方法
print([x*x for x in range(1, 6)]) 

#结果:
[1, 4, 9, 16, 25]

转自:https://zhuanlan.zhihu.com/p/66488546

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值