优雅你的python代码

作为程序员,要从平凡写出优雅。

本文每两断代码为一个模块去理解:

  1. 关于python中多变量赋值:
a = 0 
b = 1
c = 2

优雅起来:
使用元祖语法

a, b, c = 0, 1, 2
  1. 序列解包:
 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]

  1. 减少中介变量,少嵌套
name = 'Hello, World!!'
a = name.replace.(',','')
b = a.replace.('!!','')
print(b)
name = 'Hello, World!!'
b = name.replace.(',','').replace.('!!','')
print(b)
  1. 三目运算 if … else…
 a = 100
 if a>=0:
 	b = a
 else:
 	b = -a
 print(b)

优雅起来:

a = 100
b= a if a>=0 else -100

  1. 区间判断
score = 100
if score >= 50 and score < 60
	print('及格')

优雅起来
链式判断

score = 100
if 50 <= score < 60:
	print('及格')
  1. 判断是否为多个值之一
if num in == 1 or num == 'd' or num == '2':
	print(num)

使用关键字in

if num in (1,'d','2'):
	print(num)

  1. 判断是否为空列表,空字典,空字符串
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
  1. 诸多条件是否至少有一个成立
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
  1. 诸多条件是否全部成立
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
  1. 推导式
## 计算 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]])
  1. 同时遍历序列的元素和元素下标
 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)
  1. 显示循环进度

这里说每个一秒打印一行结果

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)

你可能感兴趣的:(Python)