2013-12-20 121 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

非常感谢。好多了! –