2017-10-10 33 views
3

如何避免將代碼拆分爲兩個單獨的部分? 我試圖只調用一次「DoSomething _...」函數,但在兩種情況下都可以工作。 我可能會爲此添加更多「for(s)」,問題是我必須處理單獨的代碼部分。如何避免在for + if鏈中重複代碼?

for first in FIRST_LIST: 
     for second in SECOND_LIST: 
      for third in THIRD_LIST: 
       if third!='Some specific thing': 
        for fourth in FOURTH_LIST: 
         DoSomething_K_x_fourth_Times(first,second,third,fourth) 
       else: 
        forth=0 
        DoSomething_K_Times(first,second,third,fourth) 
+0

'用於闡述FORTH_LIST如果第三=「一些具體的事情」別的[0]:' – jasonharper

+2

四年的序通常被拼寫爲「第四」,而不是「規定」。 「Forth」這個詞的意思是不同的,沿着「前進」的方向。 –

+0

@jasonharper will else [0]分支會執行DoSomething _...嗎? – Elliad

回答

2

創建具有單個項目[0]FOURTH_LIST根據條件的列表,並且迭代列表:

for first in FIRST_LIST: 
    for second in SECOND_LIST: 
     for third in THIRD_LIST: 
      if third == 'Some specific thing': 
       a_list = [0] 
      else: 
       a_list = FOURTH_LIST 
      for fourth in a_list: 
       DoSomething_K_x_fourth_Times(first, second, third, fourth) 

UPDATE

分配不同的功能的可變(func在下面的代碼)取決於條件,並調用該函數。

for first in FIRST_LIST: 
    for second in SECOND_LIST: 
     for third in THIRD_LIST: 
      if third == 'Some specific thing': 
       a_list = [0] 
       func = DoSomething_K_x_fourth_Times 
      else: 
       a_list = FOURTH_LIST 
       func = DoSomething_K_Times 

      for fourth in a_list: 
       func(first, second, third, fourth) 
+1

但是這是一個不同的函數被調用,並且您永遠不會將FORTH_LIST重置爲之前的狀態。 –

+0

@DanielH,啊,我錯過了。我會更新答案。謝謝你指出。 – falsetru

+2

您仍然用'[0]'覆蓋'FOURTH_LIST'。 – VPfB

0
def DoSomething_K_Times(first,second,third,splitpoint): 
     for x in splitpoint: 
      ... 

    for first in FIRST_LIST: 
     for second in SECOND_LIST: 
      for third in THIRD_LIST: 
       if third != 'Some specific thing': 
        DoSomething_K_Times(first,second,third,FOURTH_LIST) 
       else: 
        DoSomething_K_Times(first,second,third,[0]) 
+0

我不明白爲什麼我會多次定義一個函數。 – Elliad

+1

@CezC你是對的,這是沒有必要的。代碼已被編輯 – englealuze