Python中能否实现不重复调用函数的单行写法,校验返回值在允许列表时赋值否则用默认值?
实现方案
- 最优方案(Python 3.8+ 推荐)
使用Python原生的**海象运算符:=**实现,全程仅调用1次some_func,无冗余开销:
def some_func(): return 'foo' allowed_list = ['foo', 'bar'] value = res if (res := some_func()) in allowed_list else 'default'
执行逻辑:先执行some_func()得到返回值并绑定到临时变量res,判断res在允许列表内则将res赋值给value,否则使用预设默认值,完全匹配需求。
- 低版本兼容方案(Python <3.8 不支持海象运算符时使用)
通过生成器表达式配合next实现,同样仅调用1次目标函数:
value = next((res for res in [some_func()] if res in allowed_list), 'default')
执行逻辑:先把some_func()的返回值存入单元素列表作为判断源,生成器会遍历该列表校验值是否在允许列表中,符合则返回该值,不符合则返回next的第二个参数作为默认值。
内容的提问来源于stack exchange,提问作者dranobob
相关产品推荐
相关产品推荐

