许多 if 语句的替代方案?

Den*_*kan 5 python if-statement python-3.x

所以我有3个不同的变量。

model 是一个字符串并定义了 iPhone 模型。

storage 是一个定义电话存储的整数。

最后是价格,它是一个定义手机价格的整数。

例子:

model = iPhone 7
storage = 64 (GB)
price = 700 ($)
Run Code Online (Sandbox Code Playgroud)

另一个例子:

model = iPhone 5s
storage = 16
price = 150
Run Code Online (Sandbox Code Playgroud)

现在我想让我的程序通知我是否可以通过购买和转售来达成一笔好交易,我的问题是我如何以最有效的方式做到这一点?

我知道我可以使用 if 语句,但是有什么方法可以避免我编写大量不同的 if 或 elif 语句?

例子:

if model == "iPhone 7" and storage == 64 and price <= 700:
print("do_something")
Run Code Online (Sandbox Code Playgroud)

这只是 1 个模型和存储选项的大量代码。如果我要使用这种方法,我将不得不再写 29 个。

Pri*_*mar 0

在这种情况下,我更喜欢字典。

创建不同的处理程序(函数),根据传递的项目和数据执行特定任务。请参阅以下代码:

# Different handlers, each takes keyword args and can work specific task
def fun1(**kwargs):
    print (kwargs)
    print("fun1")


def fun2(**kwargs):
    print("fun2")

def fun3(**kwargs):
    print("fun3")

def fun4(**kwargs):
    print("fun4")


# Example data. key is phoneModel_storage
a = {
    'iPhone1_64': {
        "storage": 64,
        "action": fun1,
        "price":1235
    },
    'iPhone1_32': {
        "storage": 64,
        "action": fun3,
        "price":1235
    },
    'iPhone2_16': {
        "storage": 16,
        "action": fun1,
        "price":1235
    },
    'iPhone3_32': {
        "storage": 32,
        "action": fun3,
        "price":1235
    },
    'iPhone4_128': {
        "storage": 128,
        "action": fun4,
        "price":1235
    },
}

model = "iPhone1"
storage = 64

data = a.get(model + "_" + str(storage), None)
if data:
    data['action'](**data)
Run Code Online (Sandbox Code Playgroud)