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

标签 python for-loop coding-style refactoring nested-loops

我有一个函数可以检查字符串中的子字符串。根据在字符串中找到的子字符串的类型,我调用一个独特的函数并将其存储在变量 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 循环中包含通用修改 xreturn 的代码块,而不是 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")

关于python - 重构这些嵌套的 for/else 循环的最 pythonic 方式(如果有的话)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128555/

相关文章:

Python reportlab 在第一页完全充满文本后动态创建新页面

python - Notify.Notification 中的 PyGObject 进度条

c# - 循环 10 次添加输入,在 C# 中使用 for 和 do while 循环?

python - 打印全名python的第一个字母

c# - 有人更改 Visual Studio 默认的支撑样式吗? - 有标准吗?

python - 按顺序固定列

用于在长度为 2 的列表中查找另一个元素的 pythonic 解决方案

java - java最大和最小输入的建议

python - 如何设计一个有很多配置选项的程序?

c++ - GUID的唯一性