python - 有没有办法减少这个问题的嵌套 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
解决方案
为什么不使用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
推荐阅读
- c# - 关于 open Method(MySQL, Connector/Net) 的作用
- json - 如何使用 SWIFT 通过 JSON 将数据从多个视图控制器发布到服务器
- php - 如何将输入字段的 IF 条件放入联系表单(PHP,CODEIGNITER)
- dns - /etc/network/interfaces:4:具有空值的选项
- sql-server-2008 - 图表横轴标签间隔
- vue.js - nuxt 基础组件未在道具绑定图像上显示文件加载器路径
- postgresql - PostgreSQL 数据库同步
- java - 在 Textview 中使用 HTML 标签形成一个从外部文件读取数据的表格
- angular - 如何在角度组件之前捕获已解析的数据?
- django - Django 测试 - 类型错误:int() 参数必须是字符串、类似字节的对象或数字,而不是“用户”