【问题标题】:Python - How to count how many If/Else statements existPython - 如何计算存在多少 If/Else 语句
【发布时间】:2021-12-26 18:47:02
【问题描述】:

我想计算我的函数中有多少个 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

【问题讨论】:

  • 您可以加载包含该函数的源代码文件,然后使用简单的文本搜索(不可靠)或创建抽象语法树(模块“ast”)并进行处理。
  • 这看起来有点像 X/Y 问题。您可以计算未编译代码中的语句(如上面的注释所解释的),但是一旦在代码中,您就不能轻松地计算所有潜在的代码路径,除非您确保它们都被访问过,并以某种方式“记录”它。如果您再次发布,请尝试解释您的代码的目的是什么。
  • 我想数一下这个if statement 有多大。在这种情况下,我可以数 3。1 开头:if type == 1:,中间 2:elif type == 2:,底部 3:else:

标签: python if-statement count python-3.10


【解决方案1】:

不要使用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)

究竟将什么放入字典中作为值取决于...您能否概括该算法,以便您只需将值放入字典而不是实际代码?伟大的。否则,将函数放入字典中:

types = {1: lambda: ..., 2: some_func, 3: self.some_method}

...

types[type]()

【讨论】:

    【解决方案2】:

    由于您使用的是 Python 3.10,因此您可以使用新的 match 运算符。一个例子:

    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)
    

    【讨论】:

    • unknown_command_ 有什么区别?如何将变量x设置为有多少个case?
    • unknown_command 是什么意思? _ 是一个永远不会失败的选项。正如它在文档中所写,Note the last block: the “variable name” _ acts as a wildcard and never fails to match. If no case matches, none of the branches is executed.
    • 嗯,我搜索了一下,是的,你一定是对的。在我发现的来源中,它的用法与_ 完全相同。所以它似乎是一个替代方案。但奇怪的是,原始来源中没有此类信息。
    • 如何将变量x设置为有多少个case?
    • 更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    相关资源
    最近更新 更多