2013-12-08 73 views
1

我目前有一條很長的if語句,看起來很醜,而且我相當確定是不正確的。它看起來像這樣。替代long 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') 

我該如何去簡化這一長條件列表?

回答

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) 
+0

謝謝,這個工作非常好,一些小的調整。我必須改變'如果self.folderactive.isChecked:'如果checkbox.isChecked:' –

+0

@josh,啊..這是我的錯誤。我修復了代碼。感謝您的評論。 – falsetru

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') 
1

你應該使用關聯數組:複選框號碼爲索引,文件夾名稱爲值。