有没有比使用if / elif / elif等更有效的方法?

时间:2020-08-14 09:17:05

标签: python

我想知道是否有比问它更有效的方法:是吗?没有?好吧,这是吗?没有?好吧,这是吗?等。我想要它,所以我只能说是这样

if this = this:
    do this
elif this = that:
    do that
elif this = these
    do these
elif this = those
    do those

我想变得更有效率。

3 个答案:

答案 0 :(得分:2)

改为使用字典,并假设thisthatthesethose是函数:

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())

答案 1 :(得分:0)

您可以创建函数,将它们的名称作为值存储在字典中,其键对应于变量可以采用的可能值。键也可以是整数,这里我使用了字符串键。

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()

答案 2 :(得分:0)

最有效的选择实际上取决于您的实际需求。这里的另一个选择是三元运算符,可以将其链接起来

this() if this else that() if that else those() if those else these() if these

根据您的代码和用法,您也许可以将其重构为也使用速记三元运算符

this or that

...这将做第一件事,评估结果为true,但不会为单独的条件留出空间。但是,您可以使用

添加单独的条件
test and this or that

这样的测试和这个都需要评估为true,否则需要评估“ that”。如果“ this”和“ that”都是真实的表述,则“ test”的行为类似于您的情况。

如果愿意,还可以使用真实性将其索引到元组中。...

(do_if_false, do_if_true)[test]

对我来说,这是一个不太易读和伏都教的东西,但是“测试”有效地求值为0或1,并返回该索引处的表达式。但是,这还将评估所有表达式,除非您采取以下额外步骤:

(lambda: do_if_false, lambda: do_if_true)[test]
相关问题