簡體   English   中英

使用函數簡化代碼塊 [Python]

[英]Simplifying code blocks with functions [Python]

我正在尋找一種通過函數簡化代碼的方法。 我的操作的 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)

我的代碼運行良好,我只是想在 function 中充分利用它,並且僅與這些小的 if 條件不同。 我找不到簡化它的方法,我什至不確定是否有。

如您所見,我做了一些小功能,但我認為會有更好的方法來簡化整個構造。

不幸的是無法測試它,因為沒有定義多個變量和方法,但它似乎工作。 如果您願意,也許使用is_dir bool 變量而不是 elem 會更好:用is_dir替換elem並將以下行添加到 function 的開頭:

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)

我用@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)

暫無
暫無

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

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