关于Python中一段布尔表达式的逻辑化简与修正方案的确认咨询
关于Python中一段布尔表达式的逻辑化简与修正方案的确认咨询
你分析得完全正确!咱们来把这段逻辑拆解清楚:
首先看你遇到的原代码:
if not filename.endswith(".dat") and ( filename.endswith(".dat") or not filename.endswith(".cup") ): raise RuntimeError( "Waypoint file {} has an unsupported format.".format( waypoint_file.filename ) )
你把filename.endswith(".dat")设为A,filename.endswith(".cup")设为B,将表达式简化为not A and (A or not B)的思路非常清晰,接下来的分情况推导也完全没问题:
- 当A为False(文件不是
.dat后缀):表达式会简化成True and (False or not B),最终等价于not B——也就是说只有当文件也不是.cup后缀时,才会触发这个错误 - 当A为True(文件是
.dat后缀):表达式直接变成False and (...),结果永远是False,不会进入报错逻辑
而你判断原代码的意图是当文件后缀既不是.dat也不是.cup时提示格式不支持,这个理解完全准确,但原代码确实没实现这个逻辑。
正确的写法应该是直接判断两种后缀都不满足,用两种方式都可以:
- 直白版:
if not filename.endswith(".dat") and not filename.endswith(".cup"): raise RuntimeError(f"Waypoint file {waypoint_file.filename} has an unsupported format.")
- 用德摩根定律简化的版本(逻辑上完全等价,可读性看个人习惯):
if not (filename.endswith(".dat") or filename.endswith(".cup")): raise RuntimeError(f"Waypoint file {waypoint_file.filename} has an unsupported format.")
备注:内容来源于stack exchange,提问作者user3765883
相关产品推荐
相关产品推荐

