gpt4 book ai didi

python - 使用页面属性 sortIndex 进行树遍历

转载 作者:太空宇宙 更新时间:2023-11-03 19:35:37 25 4
gpt4 key购买 nike

我正在基于从名为 Pages 的 db.Model 检索的列表构建树结构。

每个页面条目都有一个parentKey 属性,它是一个db.SelfReferenceProperty() 和一个名为sortIndex 的db.IntegerProperty()

我获取列表并调用一个方法来遍历列表并创建一个嵌套的字典作为我的树。我获取整个列表的原因是我想跳过多个查询。

pages = Pages.gql('ORDER BY sortIndex').fetch(1000)
build_tree(pages)

和构建树:

def build_tree(nodes, *args):
# create empty tree to fill
tree = {}
build_tree_recursive(tree, None, nodes, *args)

return tree

def build_tree_recursive(tree, parent, nodes, *args):
# find root children, first level nodes have no parentKey
if parent is None:
children = [n for n in nodes if n.parentKey == None]
# find children
else:
children = [n for n in nodes if n.parentKey is not None and n.parentKey.key() == parent]

# build a subtree for each child
for child in children:
# start new subtree
key = child.key()
# Use page entry key as unique dict key
tree[key] = { 'page' : child, 'children' : {}}
# call recursively to build a subtree for current node
build_tree_recursive(tree[key]['children'], key, nodes)

问题是列表被重新排列并且不遵循 det ORDER BY。我认为这是因为当找到合适的父页面时,每个页面都会放入列表中。但即使是第一级(具有 parentKey == None 的页面)也会以错误的顺序返回。

我尝试使用树[str(i) + '_' + str(key)] 上的循环计数器设置前缀,但仍然没有以正确的顺序返回。

那么问题是如何让它们按正确的顺序排列?

编辑[已解决]:

见下文

最佳答案

为了保留作为参数发送到 build_tree 的列表的顺序,我转向了不同的角度。我使用列表代替,顺序保持不变:

def build_tree(nodes, *args):
# create empty tree to fill
t = {}
# First group all pages w/ same parent
for node in nodes:
if node.parentKey is None:
key = 'root'
else:
key = node.parentKey.key()

if not t.has_key(key):
t[key] = []

t[key].append({ 'page' : node, 'children' : []})

pageTree = t['root']
# Iterate over there
build_page_tree(pageTree, t)

return pageTree

def build_page_tree(pageTree, nodes):
#Loop over selected list
for parent, node in nodes.iteritems():
# We don't need to loop over first level node
if parent is not 'root':
# Loop over current level in page tree
for item in pageTree:
# Match keys
if item['page'].key() == parent:
# Save node as child
item['children'] = node
# Only need to loop over childs if they are present
build_page_tree(item['children'], nodes)

关于python - 使用页面属性 sortIndex 进行树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3708714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com