如何简化该Python if判断语句?能否将条件赋值给变量后使用?
问题1:是否可以将判断条件赋值给变量后再执行逻辑
完全可以。判断表达式的返回结果本身就是布尔值(True/False),你可以直接把整个表达式赋值给自定义变量,后续直接用变量做判断即可,还能大幅提升代码可读性。
问题2:if语句简化方案
基础简化
你原有代码里的"Change".lower()这类写法是冗余的,固定字符串调用lower()的结果是固定值,直接写最终的字符串即可,不需要每次判断都执行一次方法调用:
# 直接赋值判断结果到变量 next_permission = g < 20 and f >= 90 and c == "change" and e != "operate" and t == "yes" if next_permission: print("Go to the next part")
语义化拆分优化
如果希望后续维护更方便,可以把不同维度的判断拆分为单独的变量,见名知意:
# 数值类条件判断 g_match = g < 20 f_match = f >= 90 # 字符串类条件判断 c_match = c == "change" e_match = e != "operate" t_match = t == "yes" next_permission = g_match and f_match and c_match and e_match and t_match if next_permission: print("Go to the next part")
多条件集合简化
如果后续判断条件还会继续增加,可以用all()函数批量判断,代码会更整洁:
next_permission = all([ g < 20, f >= 90, c == "change", e != "operate", t == "yes" ]) if next_permission: print("Go to the next part")
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

