long if语句的替代方案

时间:2013-12-08 15:31:11

标签: python-2.7 if-statement conditional

我目前有一个很长的if语句,看起来很难看,我相当肯定是不合适的。它看起来像这样。

if self.folderactive.isChecked:
    folders.createDir('Desktop')
elif not self.folderactive.isChecked:
    folders.deleteDir('Desktop')

if self.folderactive_2.isChecked:
    folders.createDir('Documents')
elif not self.folderactive_2.isChecked:
    folders.deleteDir('Documents')

if self.folderactive_3.isChecked:
    folders.createDir('Downloads')
elif not self.folderactive_3.isChecked:
    folders.deleteDir('Downloads')

if self.folderactive_4.isChecked:
    folders.createDir('Music')
elif not self.folderactive_4.isChecked:
    folders.deleteDir('Music')

if self.folderactive_5.isChecked:
    folders.createDir('Pictures')
elif not self.folderactive_5.isChecked:
    folders.deleteDir('Pictures')

if self.folderactive_6.isChecked:
    folders.createDir('Public')
elif not self.folderactive_6.isChecked:
    folders.deleteDir('Public')

if self.folderactive_7.isChecked:
    folders.createDir('Templates')
elif not self.folderactive_7.isChecked:
    folders.deleteDir('Templates')

if self.folderactive_8.isChecked:
    folders.createDir('Videos')
elif not self.folderactive_8.isChecked:
    folders.deleteDir('Videos')

我如何简化这一长条件的条件?

3 个答案:

答案 0 :(得分:2)

首先,所有elif ...子句都可以写成else:

多个if .. else ..可以表示为循环:

checkbox_directory_pairs = [
    (self.folderactive, 'Desktop'),
    (self.folderactive_2, 'Documents'),
    (self.folderactive_3, 'Downloads'),
    ...
]

for checkbox, directory in checkbox_directory_pairs:
    if checkbox.isChecked:
        folders.createDir(directory)
    else:
        folders.deleteDir(directory)

答案 1 :(得分:1)

首先,您可以简化这样的声明:

if self.folderactive.isChecked:
    folders.createDir('Desktop')
elif not self.folderactive.isChecked:
    folders.deleteDir('Desktop')

if self.folderactive.isChecked:
    folders.createDir('Desktop')
else:
    folders.deleteDir('Desktop')

答案 2 :(得分:1)

您应该使用关联数组:复选框编号作为索引,文件夹名称作为值。