首页 > 解决方案 > 有没有办法减少这个问题的嵌套 if/elif 语句的数量?

问题描述

我试图找到两个数字(totMax 和 totMin)中的最大值,每个数字对应的未知值列表(totMax 到 maxList 和 totMin 到 minList)是相同的长度。我需要将与两个数字中的最大值对应的列表存储在变量“最高”中,假设两个数字都低于 20。如果只有一个数字满足条件,那么将存储该数字的对应列表。存储在 totMax 中的数字始终高于存储在 totMin 中的数字。有没有更简洁的方法来做到这一点?

if totMax > 20 and totMin > 20: 
      raise ValueError(f"Both out of range")
    elif totMax <= 20:
      highest = maxList
    elif totMin <= 20:
      highest = minList
    return highest 

标签: pythonpython-3.xif-statementconditional-statements

解决方案


为什么不使用max()命令:

if totMax > 20 and totMin > 20:
    raise ValueError(f"Both out of range")
else:
    highest=max(totMax,totMin)
    return highest

或者

因为:

存储在 totMax 中的数字始终高于存储在 totMin 中的数字。

if totMax > 20 and totMin > 20:
    raise ValueError(f"Both out of range")
else:
    highest=totMax
    return highest

推荐阅读