Python

重构Python代码tips

2020-11-26  本文已影响0人  弦好想断
def get_content(entry):
    for block in entry.get_blocks():
        yield block

重构后:

def get_content(entry):
    yield from entry.get_blocks()
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 的元素,它可以立即返回。

上一篇下一篇

猜你喜欢

热点阅读