如何解决用函数简化代码块 [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)
我的代码运行良好,我只是想在函数中充分利用它,并且仅与这些小的 if 条件不同。我找不到简化它的方法,我什至不确定是否有。
如你所见,我做了一些小功能,但我认为会有更好的方法来简化整个结构。
解决方法
很遗憾无法测试,因为没有定义多个变量和方法,但它似乎可以工作。也许使用 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"],cmds)
if res is not None:
notFound.append(res)
else:
do_stuff(item["path"][:-1],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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。