python - Python:从脚本中删除冗余行

python - Python:从脚本中删除冗余行,第1张

上下文:我已经学习了几个月的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 个答案:

答案 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条回复