本文每两断代码为一个模块去理解:
a = 0
b = 1
c = 2
优雅起来:
使用元祖语法
a, b, c = 0, 1, 2
colors = ['red', 'black', 'yellew', 100]
red = colors[0]
black = colors[1]
yellew = colors[2]
num = colors[3]
优雅起来:
序列自动解包
red, black, yellew, num = ['red', 'black', 'yellew', 100]
name = 'Hello, World!!'
a = name.replace.(',','')
b = a.replace.('!!','')
print(b)
name = 'Hello, World!!'
b = name.replace.(',','').replace.('!!','')
print(b)
a = 100
if a>=0:
b = a
else:
b = -a
print(b)
优雅起来:
a = 100
b= a if a>=0 else -100
score = 100
if score >= 50 and score < 60
print('及格')
优雅起来
链式判断
score = 100
if 50 <= score < 60:
print('及格')
if num in == 1 or num == 'd' or num == '2':
print(num)
使用关键字in
if num in (1,'d','2'):
print(num)
i,y,z = [1,2,3], {
}, ''
if len(i)>0:
print('...')
if len(y)>0:
print('...')
if len(z)>0:
print('...')
优雅起来:
隐含类型转换直接判断
i,y,z = [1,2,3], {
}, ''
if i:
pass
if y:
pass
if z:
pass
book, card, num = 10, 20, 30
if book < 30 or card <30 or num < 30:
printy('...')
优雅起来
使用any函数
book, card, num = 10, 20, 30
if any([ book<30, card<30, num <30 ]):
pass
book, card, num = 10, 20, 25
if book < 30 or card <30 or num < 30:
printy('...')
优雅起来
使用any函数
book, card, num = 10, 20, 30
if all([ book<30, card<30, num <30 ]):
pass
## 计算 a 中全部数值并求和
a = [1,2,3,'dadada',4,5]
list = []
for i in a:
if isinstance(i,(int,float)):
list.append(i)
sum(list)
优雅起来
推导式
a = [1,2,3,'dadada',4,5]
sum([i for i in a if type(i) in [int,float]])
colors = ['red', 'black', 'yellew', 100]
for i in range(len(colors )):
print(i:':',colors[i] )
优雅起来
使用enumerate函数生成下标和元素对
colors = ['red', 'black', 'yellew', 100]
for i,s in enumerate(colors):
print(i,':',s)
这里说每个一秒打印一行结果
import time
for i in range(100):
times.sleep(0.1)
print(i)
import time
for i in range(100):
times.sleep(0.1)
print(i, end='\r')
def process_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()
i,n = 0,100
for i in range(n):
time.sleep(0.1)
process_bar(i+1,n)