用函数简化代码块 [Python]

时间:2021-03-29 17:55:48

标签: python function simplify

我正在寻找一种通过函数来​​简化我的代码的方法。我的 90% 的操作都是相等的,只是与 if 条件不同。

例如

if isFile:
    
    fFound = False
    for key in files:
        if item["path"] in key:
            fFound = True
            for c in cmds.keys():
                if item["path"] in cmds[c]["files"]:
                    ifxchecker(item["requiredIFX"], cmds[c]["ifx_match"])

            outputCFG()

    if not fFound:
        notFound.append(item['path'])


else:
    dir = item["path"][:-1]
    pFound = False
    for key in files:
        if dir in key:
            pFound = True
            for c in cmds.keys():
                for file in cmds[c]["files"]:
                    if dir in file:
                        ifxchecker(item["requiredIFX"], cmds[c]["ifx_match"])

            outputCFG()

    if not pFound:
        notFound.append(dir)

我的代码运行良好,我只是想在函数中充分利用它,并且仅与这些小的 if 条件不同。我找不到简化它的方法,我什至不确定是否有。

如你所见,我做了一些小功能,但我认为会有更好的方法来简化整个结构。

2 个答案:

答案 0 :(得分:0)

很遗憾无法测试,因为没有定义多个变量和方法,但它似乎可以工作。也许使用 is_dir bool 变量代替 elem 会更好,如果您愿意:将 elem 替换为 is_dir 并将以下行添加到函数的开头:

elem = item["path"][:-1] if is_dir else item["path"] 
def do_stuff(elem, files, item, cmds, notFound):
    fFound = False
    for key in files:
        if elem in key:
            fFound = True
            for c in cmds.keys():
                if elem in cmds[c]["files"]:
                    ifxchecker(item["requiredIFX"], cmds[c]["ifx_match"])

            outputCFG()

    if not fFound:
        return elem


if isFile:
    res = do_stuff(item["path"], files, item, cmds)
    if res is not None:
        notFound.append(res)
else:
    do_stuff(item["path"][:-1], files, item, cmds)
    if res is not None:
        notFound.append(res)

答案 1 :(得分:0)

我用@azro 方法解决了这个问题:

def cfgFunction(x):
    global file
    fFound = False
    for file in files:
        if x in file:
            fFound = True
            for group in cmds.keys():
                if x in cmds[group]["files"]:
                    ifxchecker(item["requiredIFX"], cmds[group]["ifx_match"])

            outputCFG()
if not fFound:
    notFound.append(x)
相关问题