您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

避免“ if x:return x”语句的Python方法

避免“ if x:return x”语句的Python方法

您可以使用循环:

conditions = (check_size, check_color, check_tone, check_flavor)
for condition in conditions:
    result = condition()
    if result:
        return result

这样做还有一个好处,就是您现在可以使条件数可变。

您可以使用map()+filter()(Python 3版本,使用Python 2中的future_builtins版本)来获取一个这样的匹配值:

try:
    # Python 2
    from future_builtins import map, filter
except ImportError:
    # Python 3
    pass

conditions = (check_size, check_color, check_tone, check_flavor)
return next(filter(None, map(lambda f: f(), conditions)), None)

但是,如果更具可读性,则值得商bat。

一个选择是使用生成器表达式:

conditions = (check_size, check_color, check_tone, check_flavor)
checks = (condition() for condition in conditions)
return next((check for check in checks if check), None)
python 2022/1/1 18:42:45 有333人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶