压缩多个if语句

2024-05-29 11:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我的python代码如下所示:

if imput == "con":
    print "%.6f" % (con_getinfo["balance"])
elif imput == "xra":
    print "%.6f" % (xra_getinfo["balance"])
elif imput == "neg":
    print "%.6f" % (neg_getinfo["balance"])
elif imput == "grf":
    print "%.6f" % (grf_getinfo["balance"])
elif imput == "ninja":
    print "%.6f" % (ninja_getinfo["balance"])

现在我想让它看起来不那么重复,像这样:

if imput == con or imput == xra or imput == neg or imput == grf or imput == ninja:

但我不知道如何给每个条件分配适当的反应。你知道吗


Tags: or代码if条件conprintbalanceelif
2条回答

这可以说是个骗局,但简而言之。。。python的方法是使用字典。可能有更好的方法来重构它,但首先:

mydict = {"con": con_getinfo,
          "xra": xra_getinfo,
          "neg": neg_getinfo,
          "grf": grf_getinfo,
          "ninja" : ninja_getinfo}

lookup = mydict.get(imput)
if lookup: #won't fail if imput isn't on of the options
    print "%.6f" % (lookup["balance"])

您可以在字典中存储对函数的引用,然后只需简单的查找:

response = {
    "con": con_getinfo,
    "neg": neg_getinfo,
    ...
}
print "%.6f" % (response[imput]["balance"])

相关问题 更多 >

    热门问题