重构Python代码tips
2020-11-26 本文已影响0人
弦好想断
- 将内部循环中的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()
- 使用 any() 而不是用于循环
常见的模式是,我们需要查找是否集合中的一个或多个项符合某些条件。这可以通过 for 循环完成,例如:
found = False
for thing in things:
if thing == other_thing:
found = True
break
更简洁的方法,是使用 Python 的 any() 和 all()内置函数,来清楚地显示代码的意图。
found = any(thing == other_thing for thing in things)
当至少有一个元素计算为 True 时,any() 将返回 True,只有当所有元素都计算为 True 时,all() 将返回 True。
如果对 any() 的调用找到一个值为 True 的元素,它可以立即返回。