首页 > 解决方案 > 替换一系列 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_...) 都在另一个文件中定义并在开头导入。

虽然我对它的清除和功能感到满意,但我认为这不是最好的方法。有更好的选择吗?

标签: pythonif-statement

解决方案


是的,有更好的方法。不幸的是,python 没有switch语句,但它确实有字典。你可以做的是这样的:

mapping = {"s0":in_S0, "k":in_k .... }
mapping[change.lower()]()

但是请注意,连续使用几个 if 语句本身并没有错,有时这只是最好的解决方案。如果您与缺乏经验的开发人员一起工作,那么编写上述代码可能会使他们感到困惑。


推荐阅读