我想计算我的函式中有多少条 If/Else 陈述句。
我的代码如下所示:
def countdown(type):
    if type == 1:
        //code
    elif type == 2:
       //code
    else:
        print(f"You have reached the end of the script. "
              f"The maximum type of countdowns are: {x}")
        exit(1)
在哪里x,应该有 if 查询的数量(If/Else)。在这种情况下,有 3 个查询。如果我在此函式中创建另一个 if/else 查询,则不必更改脚本底部的警告。
这甚至可能吗?
我正在使用 Python 3.10
uj5u.com热心网友回复:
不要使用if..else,而是使用字典或串列:
types = {
    1: ...,
    2: ...
}
try:
    types[type]
except KeyError:
    print(f"You have reached the end of the script. "
          f"The maximum type of countdowns are: {len(types)}")
    exit(1)
究竟将什么放入 dict 作为值取决于......你能概括这个算法,所以你只需要将一个值放入 dict 而不是实际代码?伟大的。否则,将函式放入字典中:
types = {1: lambda: ..., 2: some_func, 3: self.some_method}
...
types[type]()
uj5u.com热心网友回复:
由于您使用的是 Python 3.10,因此您可以使用 newmatch运算子。一个例子:
def countdown(type):
    match type:
        case 1:
            # code
        case 2:
            # code
        case _:
            print(f"You have reached the end of the script. "
                  f"The maximum type of countdowns are: {x}")
            exit(1)
对我来说,这是一个比一个更易读的解决方案dict。
如何计算选项的数量,让我们考虑一下我们有n不同且逻辑上分开的选项。在这种情况下,我建议您enum:
from enum import IntEnum
class CountdownOption(IntEnum):
    FIRST = 1
    SECOND = 2
    # ...
# ...
def countdown(type):
    match type:
        case CountdownOption.FIRST:
            # code
        case CountdownOption.SECOND:
            # code
        case _:
            print(f"You have reached the end of the script. "
                  f"The maximum type of countdowns are: {len(CountdownOption)}")
            exit(1)

 
							 
										
										 
										
										 
										
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										 
										
										
0 评论