python - 替换一系列 if 语句
问题描述
我正在编写代码,用户输入一个字符串,该字符串是可能的选择之一(先前输入的参数)。
根据所做的选择,代码运行正确的函数,用于要求用户输入数据并进行验证。
这是我的代码:
correct = input("Are all the data inserted correct? Yes/No \n")
while correct.lower() == 'no':
change = input("What would you like to change? S0, k, r, u, d, volatility, T, nodes, style, type \n")
if change.lower() == 's0':
S0 = in_S0()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() == 'k':
k = in_k()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() == 'r':
r = in_r()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() in ['u','d','vol','volatility']:
u, d, vol = in_asset()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() == 't':
T = in_T()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() == 'nodes':
nodes = in_nodes()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() == 'style':
style = in_style()
correct = input("Are all the data inserted correct? Yes/No \n")
if change.lower() == 'type':
types = in_types()
correct = input("Are all the data inserted correct? Yes/No \n")
所有函数 ( in_...
) 都在另一个文件中定义并在开头导入。
虽然我对它的清除和功能感到满意,但我认为这不是最好的方法。有更好的选择吗?
解决方案
是的,有更好的方法。不幸的是,python 没有switch
语句,但它确实有字典。你可以做的是这样的:
mapping = {"s0":in_S0, "k":in_k .... }
mapping[change.lower()]()
但是请注意,连续使用几个 if 语句本身并没有错,有时这只是最好的解决方案。如果您与缺乏经验的开发人员一起工作,那么编写上述代码可能会使他们感到困惑。
推荐阅读
- java - 使用 Apache POI XSSFWorkbook 时出现 NoClassDefFoundError
- r - 抓取拍摄位置的坐标数据和附加信息
- selenium - Google Chrome 窗口调整大小限制
- c# - 从 PowerPoint 幻灯片生成图像
- shell - 如何在 unix 的变量赋值中将文件名传递给 sed|grep|awk 命令
- reactjs - 相邻的 JSX 元素必须包含在带有引导列的封闭标记中
- mysql - 滚动 12 个月数据求和运算
- java - 下划线作为 Java 中的变量名。为什么?
- c++ - 在opencv c ++中创建线性结构元素
- excel - 使用查找功能时出现错误 91,使用 ActiveCell?