循环语句准备好多级深度

时间:2016-07-01 10:40:28

标签: python loops for-loop dictionary while-loop

我正在尝试打印类别树(带有子类别的主要类别),但我有优雅解决方案的问题,它将准备好无限级别深度。

此刻我有:

cat_id = '31'
cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + cat_id + ']'})['categories']['category']['associations']['categories']['category']

'''
cat returns dictionary:
cat [
     {'id': '32'},
     {'id': '37'},
     {'id': '48'},
     {'id': '52'},
     {'id': '54'},
     {'id': '57'},
     {'id': '58'},
     {'id': '59'},
     {'id': '1068'}
]
'''

for c in cat:
    print 'Level 2: ' + c['id']
    try:
        cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + c['id'] + ']'})['categories']['category']['associations']['categories']['category']
        for c in cat:
            print 'Level 3: ' + c['id']
            try:
                cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + c['id'] + ']'})['categories']['category']['associations']['categories']['category']
                for c in cat:
                    print 'Level 4: ' + c['id']
                    try:
                        cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + c['id'] + ']'})['categories']['category']['associations']['categories']['category']
                        for c in cat:
                            print 'Level 5: ' + c['id']
                    except:
                        pass
            except:
                pass
    except:
        pass

如您所见,我的代码的有效性取决于我将手动输入的级别。这是一个糟糕的解决方案,但只有一个我能够在这一刻工作。

如何调整该代码以便为无限级别(5,6,7,8,9,10,11,12 ...级别)做好准备,并且更加免维护。

结果:

Level 2: 32
   Level 3: 33
   Level 3: 1178
Level 2: 37
   Level 3: 1201
   Level 3: 38
   Level 3: 39
   Level 3: 40
      Level 4: 1020
      Level 4: 41
      Level 4: 42
   Level 3: 43
      Level 4: 1092
      Level 4: 1093
      Level 4: 1094
      Level 4: 1095
   Level 3: 1024
      Level 4: 44
      Level 4: 45
      Level 4: 1179
Level 2: 48
   Level 3: 49
   Level 3: 50
   Level 3: 51
   Level 3: 1128
   Level 3: 1067
   Level 3: 1133
Level 2: 52
   Level 3: 53
   Level 3: 1200
Level 2: 54
   Level 3: 55
   Level 3: 56
   Level 3: 1202
Level 2: 57
Level 2: 58
Level 2: 59
   Level 3: 60
   Level 3: 61
Level 2: 1068

1 个答案:

答案 0 :(得分:0)

我不熟悉prestashop,但你尝试过递归函数吗?

def print_levels(cat, level = 2):
    try:
        for c in cat:
            print((" " * level) + "Level {0}: {1}\n".format(level,c['id']))
            new_cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + c['id'] + ']'})['categories']['category']['associations']['categories']['category']
            if new_cat:
                print_levels(new_cat, level + 1)
            else:
                return
    except:
        return
cat_id = '31'
cat = prestashop.get('categories', options={'display':'full', 'filter[id]':'[' + cat_id + ']'})['categories']['category']['associations']['categories']['category']
print_levels(cat)