python-是否有此代码的替代方法,看起来更整洁并且更易于理解?

我有这段代码,它遍历一个集合,并检查该集合中的一项是否为文件夹,如果是,它将检查其所在的文件夹,然后根据该文件夹继续执行操作它是.我不太确定如何解释为什么会有两个循环,所以我希望你们可以看看它并理解我为什么这样做,因为没有它就无法工作.

您可以看到为什么我想知道是否可以清理…

在这种情况下,requireddirs的值为

set(['Pictures', 'Downloads', 'Public', 'Desktop'])

这是需要清理的主要代码.

neededdirs = folders.findKeyDir('active') #declares the set
for x in neededdirs: #starts the main loop
    for y in neededdirs: #starts the second loop
        if folders.getObject(neededdirs, y, 'bool'): #checks to see if the the option in the set is a folder.
            neededname = folders.getObject(neededdirs, y, 'name') #retrieves the name of the item in the set.
            if neededname == "Desktop": #this and all elif's after just check its name.
                self.folderheader1.setText(_translate("MainWindow", "Status: Active", None)) #this, the line after, and all others like it just change the text on an item if it evaluates to true.
                self.folderactive.setChecked(True)
            elif neededname == "Documents":
                self.folderheader2.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_2.setChecked(True)
            elif neededname == "Downloads":
                self.folderheader3.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_3.setChecked(True)
            elif neededname == "Music":
                self.folderheader4.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_4.setChecked(True)
            elif neededname == "Pictures":
                self.folderheader1_2.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_5.setChecked(True)
            elif neededname == "Public":
                self.folderheader1_3.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_6.setChecked(True)
            elif neededname == "Templates":
                self.folderheader1_4.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_7.setChecked(True)
            elif neededname == "Videos":
                self.folderheader1_5.setText(_translate("MainWindow", "Status: Active", None))
                self.folderactive_8.setChecked(True)

提前致谢.

解决方法:

您所有的if / elif分支仅在调用setText和setChecked的对象上有所不同.您可以将其分解为以下内容:

knownFolders = {
    "Desktop": (self.folderheader1, self.folderactive),
    "Documents": (self.folderheader2, self.folderactive_2),
    ...
}

然后,您可以将if / elif链替换为:

if neededname in knownFolders:
    header, checkBox = knownFolders[neededname]
    header.setText(_translate("MainWindow", "Status: Active", None))
    checkBox.setChecked(True)

另外,从代码中的注释来看,我认为您可以用单个列表理解替换两个嵌套循环,例如:

relevantFolders = [folders.getObject(neededdirs, d, 'name')
                   for d in neededdirs
                   if folders.getObject(neededdirs, d, 'bool')]
上一篇:Javascript For Loop替代将初始变量设置为1?


下一篇:php-如何检查另一个数组中是否存在相似的数组