2013-12-20 119 views
0

上下文:我一直在學習Python幾個月,我能夠編寫能夠工作的代碼,但通常看起來非常難看,並且包含大量不必要的代碼。但由於我的知識有限,我通常很難找到更好的方法去做事。Python:從腳本中刪除冗餘行

我想就下面的代碼可以改進的一些建議。僅供參考 - 它工作得很好,但我猜測必須有方法來改進它。我知道我在循環中重複自己,例如?

def getTableGroupTopMember_Test1(coordinates): 
    ''' 
    Depending on the number of coordinates given, this function/code returns a unique coordinate. 
    ''' 

    mylist = coordinates 

    for adc in activeDataConnections: 
     if mylist.Count == 1: 
      for table in adc: 
       if table.Name == mylist[0]: 
        print "/" 
     elif mylist.Count == 2: 
      for table in adc: 
       if table.Name == mylist[0]: 
        for topgroup in table.TopAxis.Groups: 
         if topgroup.Name == mylist[1]: 
          print topgroup.Address 
     elif mylist.Count == 3: 
      for table in adc: 
       if table.Name == mylist[0]: 
        for topgroup in table.TopAxis.Groups: 
         if topgroup.Name == mylist[1]: 
          for topmember in topgroup: 
           if topmember.Name == mylist[2]: 
            print topmember.Address 
     else: 
      print "your code is shit!" 


getTableGroupTopMember_Test1(["Table10"]) 
getTableGroupTopMember_Test1(["Table10", "profile_julesage",]) 
getTableGroupTopMember_Test1(["Table10", "profile_julesage", "_25_to_34"]) 

輸出:

/ 
/2 
/2[3] 

謝謝大家!

+1

這應該是http://codereview.stackexchange.com/填寫。該網站的設立是爲了改進工作代碼。 – iCodez

+0

不知道,非常感謝! –

回答

1

你有重複的循環。你可以通過把我沒有寫在函數裏面的代碼放進去:count1,count2,count3。

if mylist.Count == 1: 
    func = count1 
elif mylist.Count == 2: 
    func = count2 
elif mylist.Count == 3: 
    func = count3 
else 
    print "your code is shit!" 
    return 

for adc in activeDataConnections: 
    for table in adc: 
     if table.Name == mylist[0]: 
       func() 

我敢肯定,你可以在空白

+0

+1這看起來更清潔,並且仍然允許我分別維護每個案例,而不是將它聚集成一個具有條件的大循環。添加新案例也很容易,我不必擔心打破現有案例。 – MxyL

+0

非常感謝。好多了! –