python代码的优雅之处

版权声明:转载博文请注明出处。 https://blog.csdn.net/weixin_41297332/article/details/82026406

# 一.优雅你的赋值语句

# 1.为多个变量赋值
#平凡方法:逐一赋值
a = 0
b = 1
c = 2
#优雅方法:使用元组语法同时赋值
a = b = c =0,1,2

# 2.序列解包
# 平凡方法:使用下标逐一访问赋值
ls = ['daxue','22','man']
name = ls[0]
age = ls[1]
sex = ls[2]
print(name,age,sex)
# 优雅方法:序列自动解包
ls = ['daxue','22','man']
name,age,sex = ls
print(name,age,sex)

# 3.对象方法的嵌套
# 平凡方法定义中间变量,不嵌套
s = 'Python$$ is simple readable **and powerful!!**'
s1 = s.replace('$','')
s2 = s1.replace('*','')
print(s2)
# 优雅方法:使用对象方法嵌套,减少中间变量
s = 'Python$$ is simple readable **and powerful!!**'
print(s.replace('$','').replace('*',''))

# 二.优雅你的判断语句

# 4.单行if语句:if...else...三目运算符
# 平凡方法:使用普通需要换行的if...else..语句
x = - 5
if x > 0:
    y = x
else:
    y = -x
print(y)
# 优雅方法:使用单行if...else...语句.
x = - 5
y = x if x > 0 else -x
print(y)

# 5.区间判断
# 平凡方法:使用and连接两次判断
score = 78
if score >= 60 and score < 80:
    temp = 'A'
print(temp)
# 优雅方法:使用链式判断
score = 75
if 60 <= score <80:
    temp = 'A'
print(temp)

# 6.判断是否是多个取值之一
# 平凡方法:使用or连接多次相等判断
ch = "A"
if ch == 'A' or ch == 'B' or ch == 'C':
    print('OK')
# 优雅方法:使用关键字in
ch = "A"
if ch in ('A','B','C'):
    print('ok')

# 7.判断是否为空列表,空字符串,空字典
# 平凡方法:使用len函数判断长度是否大于0.
l,d,s = [1,2,3],{},''
if len(l)>0:
    print('l is not empty')
if len(d)>0:
    print('d is not empty')
if len(s)>0:
    print('s is not empty')
# 优雅方法:利用隐含类型转换直接判断.
l,d,s = [1,2,3],{},''
if l:
    print('l is not empty')
if d:
    print('d is not empty')
if s:
    print('s is not empty')

# 8.判断诸多条件是否有一个成立
# 平凡方法:使用or连接多次判断
math,physics,computer = 70,40,60
if math < 60 or physics < 60 or computer < 60:
    print('not pass')
# 优雅方法:使用any函数
math,physics,computer = 70,40,60
if any([math < 60,physics < 60,computer < 60]):
    print('not pass')

# 9.判断诸多条件是否全部成立
# 平凡方法:使用and连接多次判断
math,physics,computer = 70,80,90
if math >= 60 and physics >= 60 and computer >= 60:
    print('pass')
# 优雅方法:使用all方法
math,physics,computer = 70,80,90
if all([math >= 60,physics >= 60,computer >= 60]):
    print('pass')

# 三.优雅你的循环语句

# 10.单行循环语句:推导式
# 平凡方法:使用for循环
#过滤l中全部的数字并求和
l = [1,2,3,'abd',4]
l_filter = []
for i in l:
    if isinstance(i,(int,float)):
        l_filter.append(i)
sum(l_filter)
# 优雅方法:使用推导式:[...for...in...if..]
l = [1,2,3,'abd',4]
sum([i for i in l if type(i) in [int,float]])

# 11.同时遍历序列的元素和元素下标
# 平凡方法:
seasons = ['spring','summer','autumn','winter']
for i in range(len(seasons)):
    print(i,':',seasons[i])
# 优雅方法:使用enumerate函数生成下标和元素对
seasons = ['spring','summer','autumn','winter']
for i,s in enumerate(seasons):
    print(i,':',s)

# 12.循环显示进度
# 平凡方法:直接不断pring下标,该方法容易导致输出刷屏
import time,sys
i,n = 0,100
# for i in range(n):
#     time.sleep(0.1)
#     if (i+1)%10 == 0:print(i+1)
# 优雅方法:print下标后设置不换行并使用'\r'回车到行首以避免输出刷屏
# for i in range(n):
#     time.sleep(0.1)
#     if (i+1)%10 == 0:print(i+1,end='\r')
# 优雅方法加强版:直接像是进度条:定义progress_bar函数,直接显示进度条
def progress_bar(num,total):
    rate = float(num)/total
    ratenum = int(100*rate)
    r = '\r[{}{}]{}%'.format('*'*ratenum,' '*(100-ratenum),ratenum)
    sys.stdout.write(r)
    sys.stdout.flush()
for i in range(n):
    time.sleep(0.1)
    progress_bar(i+1,n)

# 四.优雅你的函数

# 13.使用lambda匿名函数实现简单的函数
# 平凡方法:使用def关键字
# 优雅方法:使用lambda匿名函数
l = [1,2,3,'abd',4]
print(sum(filter(lambda x: isinstance(x,(int,float)),l)))

# 14.使用yield生成器收集系列值.生成器具有惰性计算特点,被迭代才逐个计算输出值
def fibs(n):
    a,b,i = 1,1,1
    while i <= n:
        i +=1
        yield a
        a,b = b,a+b
print(list(fibs(10)))

猜你喜欢

转载自blog.csdn.net/weixin_41297332/article/details/82026406