我正在构建一个python函数,该函数返回要在select下拉字段中使用的数组。到目前为止我已经尝试了两个版本。递归循环遍历类
他们都工作,第一次返回格式正确的选择字段。但是,第一种解决方案只能深入两层。我打算为这些类别增加更多的深度。
我的第二个例子是我试图递归地做到这一点,以支持更多的级别。它的工作原理,但我想知道如何优化它,并添加类似于第一个例子的破折号。
# first example two levels deep, formatted properly with dashes
def build_choice_tree():
categories = Category.query.get(1).children
items = [(1, 'None')]
for root in categories:
items.append((root.id, root.name))
if root.children:
for subcat1 in root.children:
items.append((subcat1.id, '- ' + subcat1.name))
if subcat1.children:
for subcat2 in subcat1.children:
items.append((subcat2.id, '--' + subcat2.name))
return items
# second example goes multiple levels, needs dashes
def build_choice_tree2():
categories = Category.query.get(1).children
items = []
def loop(categories):
for category in categories:
items.append((category.id, category.name))
if category.children:
loop(category.children)
return items
result = loop(categories)
return result
你是否需要id后的空格?或者你的意思是每层有相同的长度? –
我需要在短划线和名字之间有一个空格 – Casey