Skip to main content
 首页 » 编程设计

python之重构这些嵌套的 for/else 循环的最 pythonic 方式(如果有的话)是什么

2025年05月04日12unruledboy

我有一个函数可以检查字符串中的子字符串。根据在字符串中找到的子字符串的类型,我调用一个独特的函数并将其存储在变量 x 中。最后,该函数有一个标准化的返回值,它对 x 执行几个复杂的操作,然后返回它。像这样:

def awesome(string): 
    for substring in ['AB', 'CD', 'EF']: 
        if substring in string: 
            x = do_something() 
            break 
    else: 
        for substring in ['12', '34', '56']: 
            if substring in string: 
                x = do_something_else() 
                break 
        else: 
            for substring in ['!@', '@#', '#$']: 
                if substring in string: 
                    x = do_another_thing() 
                    break 
    # Universally modifies x 
    x += complicated_thing() 
    if some_condition(x): 
        x += "Hello" 
    else: 
        x += "World" 
    return x 

三个选择最初对我来说是显而易见的:

  • 第一个是保持原样。当然,嵌套的 for/else 循环有点难看。
  • 第二个选项是在每个 for 循环中包含通用修改 x 和 return 的代码块,而不是 break ,但这似乎破坏了“不要重复自己”的原则。
  • 最后,我可以将最终代码块保存在一个新函数 function 中,并在每个 for 循环中返回 function(x),但这是否会创建一个不必要的深奥函数没什么用?

欢迎任何建议。谢谢!

请您参考如下方法:

def is_substr(input_string, substrs): 
    return any(strs in input_string for strs in substrs) 
 
def awesome(my_string): 
    if is_substr(my_string, ["A", "B", "C"]): 
        x = do_something() + complicated_thing() 
    elif is_substr(my_string, ["1", "2", "3"]): 
        x = do_something_else() + complicated_thing() 
    elif is_substr(my_string, ["!", "#", "$"]): 
        x = do_another_thing() + complicated_thing() 
    return x + ("Hello" if some_condition(x) else "World") 

如果检查的顺序无关紧要,这可以像这样进一步概括和压缩

def awesome(input_string): 
    functions_dict = { 
        ('AB', 'CD', 'EF'): do_something, 
        ('12', '34', '56'): do_something_else, 
        ('!@', '@#', '#$'): do_another_thing 
    } 
    for sub_strings, function in functions_dict.items(): 
        if any(s in input_string for s in sub_strings): 
            x = function() + complicated_thing() 
            return x + ("Hello" if some_condition(x) else "World")