【发布时间】:2013-12-31 10:55:50
【问题描述】:
我有这段代码循环一个集合,并检查集合中的一个项目是否是文件夹,如果是,它会检查它是哪个文件夹,然后继续执行基于操作的操作在什么文件夹上。我不太清楚如何解释为什么会有两个循环,所以我希望你们可以看看它并理解我为什么这样做,因为没有它就无法工作。
你可以明白为什么我想知道它是否可以清理......
在这种情况下,needdirs 的值为
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)
提前致谢。
【问题讨论】:
-
对您的问题的简短回答是“是的”。您可能会发现 this post on "switch" in Python 会激励您做得更好。
-
您的代码根本没有使用外部循环定义的
x变量。 -
既然你说这行得通,你应该把它贴在codereview 上。 SO 更多地处理编码问题,因为明确设置了 CR 以改进工作代码。
-
@FrerichRaabe 不,你是对的,它没有,我没有使用 x 变量的循环,我有循环两次遍历所需目录的内容。就像我说的那样,我不太确定如何解释为什么那里有两个循环,但如果你删除其中一个,那么代码就不能正常工作。
-
你不应该有像
folderheader1_3、1_4这样的变量名。每当你看到它时,这表明你应该使用列表或字典或可以存储的东西这些数字,所以你可以循环它们。
标签: python loops conditional