簡體   English   中英

重構這些嵌套的for / else循環的最pythonic方法是什么(如果有的話)?

[英]What's the most pythonic way (if any) to refactor these nested for/else 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 s的代碼塊,而不是break ,但這似乎破壞了“不要重復自己”的原理。
  • 最后,我救不了最后的代碼塊中的一個新的功能function和返回function(x)在每個for循環,但這是否創建一個具有很少使用不必要的深奧的功能?

任何建議表示贊賞。 謝謝!

這個怎么樣:

def check(substrings, somestring):
    return any(substring in somestring for substring in substrings)

def awesome(somestring):
    x = some_default_value
    vals = [do_something, do_something_else, do_another_thing]
    subs = [['AB', 'CD', 'EF'], ['12', '34', '56'], ['!@', '@#', '#$']]
    for val,substrings in zip(vals, subs):
        if check(substrings, somestring):
            x = val()
            break

    # Universally modifies x
    x += complicated_thing()
    if some_condition(x):
        x += "Hello"
    else:
        x += "World"
    return 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")

這也應該起作用。

def awesome(string):

    foo = [{'subs': ['A', 'B', 'C'], 'func': do_something},
           {'subs': ['1', '2', '3'], 'func': do_something_else},
           {'subs': ['!', '?', '.'], 'func': do_another_thing}
    ]

    for bar in foo:
        if any(s in string for s in bar['subs']):
            x = bar['func']()
            break

    # Universally modifies x
    x += complicated_thing()
    if some_condition(x):
        x += "Hello"
    else:
        x += "World"
    return x

一個簡單的選擇是

def awesome(string):
    count = 0
    for s in ['AB', 'CD', 'EF',
              '12', '34', '56',
              '!@', '@#', '#$']:
        count += 1
        if s in string:
            break

    fun = {'0': do_something, '1': do_something_else, '2': do_another_thing}

    x = fun.get(str(count / 3))() + complicated_thing()

    delta = 'Hello' if some_condition(x) else 'World'

    return x + delta

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM