Python 有没有比使用if/elif/elif等更有效的方法?
我想知道是否有一种更有效的方法比让它问:是这样吗?不好的,那么是这个吗?不好的,那么是这个吗?等等,我想要它,这样我就可以说是这样做那样做Python 有没有比使用if/elif/elif等更有效的方法?,python,Python,我想知道是否有一种更有效的方法比让它问:是这样吗?不好的,那么是这个吗?不好的,那么是这个吗?等等,我想要它,这样我就可以说是这样做那样做 if this = this: do this elif this = that: do that elif this = these do these elif this = those do those 我想提高效率。改用字典,假设这个,那个,这些和那些都是函数: def this(): return "
if this = this:
do this
elif this = that:
do that
elif this = these
do these
elif this = those
do those
我想提高效率。改用字典,假设
这个
,那个
,这些
和那些
都是函数:
def this():
return "this"
def that():
return "that"
def these():
return "these"
def those():
return "those"
d = {"this": this,
"that": that,
"these": these,
"those": those
}
this = "that"
r = d.get(this, None)
print(r())
您可以创建函数,将它们的名称作为值存储在字典中,键对应于您的变量可以采用的可能值。键也可以是整数,这里我使用了字符串键
def mango(quantity):
print("You selected "+str(quantity)+" mango(es).")
def banana(quantity):
print("You selected "+str(quantity)+" banana(s).")
def apple():
print("Here, have an apple")
fruits = {"m":mango, "b":banana} #key->function name
fruit = "m"
quantity = 1 #e.g. of parameters you might want to supply to a funciton
if fruit in fruit_rates: #with if-else you can mimic 'default' case
fruit_rates[fruit](quantity)
else:
apple()
最有效的选择实际上取决于你真正想要的是什么。这里的另一个选项是三元运算符,它可以链接起来
this() if this else that() if that else those() if those else these() if these
根据您的代码和使用情况,您可能还可以将其重构为使用速记三元运算符
this or that
…这将做第一件计算结果为真的事情,但不会为单独的条件留下空间。但是,可以使用添加单独的条件
test and this or that
这样,测试和这两者都需要评估为真,否则评估为“那”。如果“this”和“that”都是真实的表达式,“test”的行为与您的情况类似
如果您愿意,还可以使用truthiness索引到元组中
(do_if_false, do_if_true)[test]
对我来说,这一个可读性较差,更像巫术,但“test”的有效计算结果为0或1,返回该索引处的表达式。但是,这也将计算所有表达式,除非您对以下内容采取了额外步骤:
(lambda: do_if_false, lambda: do_if_true)[test]
这取决于你的实际问题。可能使用带有函数的
dict
。这有什么帮助吗?这将执行所有四个分支以构建字符串字典。通常情况下,您希望将函数放入字典中。实际上,您希望将函数名存储在dict
中,而不是一次运行它们的结果。感谢您的反馈,我已将字典值修改为仅包含函数名。当您尝试从字典中获取值时,您可能希望使用默认返回值None
。然后,您可以添加一个条件,其中您只调用r
,如果它不是None
。