原文链接

1.合并嵌套的if条件

太多的嵌套会使代码难以理解,这在 Python 中尤为如此,因为 Python 没有括号来帮助区隔不同的嵌套级别。应尽可能减少嵌套,如果两个条件可以用 and 合在一起,会比嵌套更易读。

if a:
	if b:
		return c
		
--------->
if a and b:
	return c

2.将重复的代码移到条件语句之外

在条件的两个分支上出现重复代码,这意味这段代码将始终执行。因此这段重复的代码可以从条件中移出,放在条件之外执行。

if sold>DISCOUNT_AMOUNT:
	total=sold*DISCOUNT_PRICE
	label=f'Total:{total}'

else:
	total=sold*PRICE
	label=f'Total:{total}'
	
--------->
if sold>DISCOUNT_AMOUNT:
	total=sold*DISCOUNT_PRICE

else:
	total=sold*PRICE

label=f'Total:{total}'

3.将内部循环中的yield替换为yield from

Python 的yield关键字有对应的为collections准备的yield from。因此无需使用 for 循环遍历集合。这使代码变短,并删除 for 中的额外变量。而且消除 for 循环后,yield from使程序运行效率提高约 15%。

def get_content(entry):
	for block in entry.get_blocks():
		yield block
	
--------->
def get_content(entry):
	yield from entry.get_blocks()

4.使用any()而不是用于循环

当至少有一个元素计算为 True 时,any() 将返回 True,只有当所有元素都计算为 True 时,all() 将返回 True。如果对 any() 的调用找到一个值为 True 的元素,它可以立即返回。

found=False
for thing in things:
	if thing==other_thing:
		found=True
		break
	
--------->
found==any(thing==other_things for thing in things)

5.用[ ]替换list( )

$ python3 -m timeit "x=list()"
2000000 loops, best of 5: 123 nsec per loop

--------->
$ python3 -m timeit "x=[]"
10000000 loops, best of 5: 31 nsec per loop

6.将重复执行的语句移出for/while循环

如果某条语句只是设置了一些变量供循环使用,则不需要在循环中。循环本身就是复杂的,因此在编写循环时,应牢记,使其更短、更容易理解。

for building in buildings:
	city="London"
	addresses.append(building.street_address,city)

--------->
city="London"
for building in buildings:
	addresses.append(building.street_address,city)

7.将循环转换成list/dictionary/set等数据结构

cubes=[]
for i in range(20):
	cubes.append(i**3)

--------->
cubes=[i**3 for i in range(20)]

8.用增量赋值代替普通赋值

-=, *=, /= and **=,但numpy中array数组不支持/=

count=count+other_value

--------->
count+=other_value

9.内部变量只使用一次

移除了不必要的变量,函数名直接能告诉你返回的结果,而state_attr变量并不能提供任何额外信息。

def state_attributes(self):
	state_attr={
		ATTR_CODE_FORMAT:self.code_format,
		ATTR_CHANGED_BY:self.changed_by
	}
	return state_arrt

--------->
def state_attributes(self):
	return {
		ATTR_CODE_FORMAT:self.code_format,
		ATTR_CHANGED_BY:self.changed_by
	}

10.用if表达式替换if语句

if condition:
	x=1
else:
	x=2

--------->
x=1 if condition else 2

11.用generator替换不必要的表达式

‘all’, ‘any’, ‘enumerate’, ‘frozenset’, ‘list’, ‘max’, ‘min’, ‘set’, ‘sum’, ‘tuple’允许你传入generator而不是collection

hat_found=any([is_hat(item) for item in wardrobe])

--------->
hat_found=any(is_hat(item) for item in wardrobe)

---------or
hat_found=any((is_hat(item)) for item in wardrobe)

12.把简单的条件放在return语句里

def function():
	if isinstance(a,b) or issubclass(b,a):
		return True
	return False

--------->
def function():
	return isinstance(a,b) or issubclass(b,a)
def function():
	hats=[item for item in wardrobe if is_hat(item)]
	if isinstance(a,b) or issubclass(b,a):
		return True
	return False

--------->
def function():
	hats=[item for item in wardrobe if is_hat(item)]
	return bool(hats or self.waring_hat())

13.添加保护条款

深层的函数很难理解,必须记住条件并带入每一子层中。

def should_i_wear_this_hat(self,hat):
	if isinstance(hat,Hat):
		current_fashion=FASHION_API.get_fashion(FASHION_TYPE.HAT)
		weather_outside=self.look_out_of_window()
		is_stylish=self.evaluate_style(hat,current_fashion)
		if weather_outside.is_raining:
			print("Damn.")
			return True
		else:
			print("Great.")
			return is_stylish
	else:
		return False

--------->
def should_i_wear_this_hat(self,hat):
	if not isinstance(hat,Hat):
		return False
	
	current_fashion=FASHION_API.get_fashion(FASHION_TYPE.HAT)
	weather_outside=self.look_out_of_window()
	is_stylish=self.evaluate_style(hat,current_fashion)
	if weather_outside.is_raining:
		print("Damn.")
		return True
	else:
		print("Great.")
		return is_stylish

14.转化if/else语句移除空的if块

if location==OUTSIDE:
	pass
else:
	take_off_hat()

--------->
if location!=OUTSIDE:
	take_off_hat()
else:
	pass

15.合并append到list声明

hats_i_own = []
hats_i_own.append('panama')
hats_i_own.append('baseball_cap')
hats_i_own.append('bowler')

--------->
hats_i_own = ['panama', 'baseball_cap', 'bowler']

16.移动变量申明到靠近使用它的地方

  • 不必在函数之外的工作空间存储变量
  • 把变量的声明和使用放在一块,这样更容易把函数分开
  • 如果把变量声明在很远的地方,如果代码有修改,可能这些变量就被遗忘了
def should_i_wear_this_hat(self, hat):
    if not isinstance(hat, Hat):
        return False

    current_fashion = get_fashion()
    weather_outside = self.look_out_of_window()
    is_stylish = self.evaluate_style(hat, current_fashion)
    if weather_outside.is_raining:
        print("Damn.")
        return True
    else:
        print("Great.")
        return is_stylish

--------->
def should_i_wear_this_hat(self, hat):
    if not isinstance(hat, Hat):
        return False

    weather_outside = self.look_out_of_window()
    if weather_outside.is_raining:
        print("Damn.")
        return True
    else:
        print("Great.")
        current_fashion = get_fashion()
		return self.evaluate_style(hat, current_fashion)

17.使用items()来获取字典中每个元素

hats_by_colour = {'blue': ['panama', 'baseball_cap']}
for hat_colour in hats_by_colour:
    hats = hats_by_colour[hat_colour]
    if hat_colour in self.favourite_colours:
        think_about_wearing(hats)

--------->
hats_by_colour = {'blue': ['panama', 'baseball_cap']}
for hat_colour,_ in hats_by_colour.items():
    if hat_colour in self.favourite_colours:
        think_about_wearing(hats)

18.简化序列比较

if len(list_of_hats)>0:
	hat_to_wear=choose_hat(list_of_hats)

--------->
if list_of_hats:
	hat_to_wear=choose_hat(list_of_hats)