我一直在嘗試為下面的代碼示例撰寫一個遞回函式,但我面臨的問題是我的回圈在下一次運行時會加倍。
def get_choices():
choices = []
nodes = Node.query.filter_by(parent_id=None).all()
for node in nodes:
choices.append((node.id, f"{node.value}"))
if node.children:
for child in node.children:
choices.append((child.id, f"-{child.value}"))
if child.children:
for c in child.children:
choices.append((c.id, f"--{c.value}"))
return choices
我目前正在處理的代碼
def get_choices():
c = Node.query.filter_by(parent_id=None).all()
return _get_choices(c)
def _get_choices(children, depth=0, prev_choices=[]):
new_choices = prev_choices
for child in children:
new_choices.append((child.id, f"{depth * '-'}{child.value}"))
if child.children:
_get_choices(child.children, depth 1, new_choices)
return new_choices
uj5u.com熱心網友回復:
我想你想要的是:
def _get_choices(nodes, depth=0):
if not nodes:
return []
for node in nodes:
yield (node.id, f"{depth * '-'}{node.value}")
yield from _get_choices(node.children, depth 1)
def get_choices():
return list(_get_choices(Node.query.filter_by(parent_id=None).all()))
我不知道究竟會發生Node什么,但是如果我對您的資料結構的理解是正確的,這將為每個節點及其每個子節點生成一個元組,一直向下,深度優先。
順便說一句:使用內置函式的名稱或關鍵字作為變數或屬性名稱通常不是一個好主意。它作業得很好,但您可能想要重命名id(這是一個內置函式)。
由于我沒有要測驗的資料,下面是一個對樣本資料執行相同操作的示例:
class Node:
def __init__(self, ident, value, children=None):
self.ident = ident
self.value = value
self.children = children if children else []
data = [
Node(1, 'a', [Node(2, 'b'), Node(3, 'c', [Node(4, 'd')])]),
Node(5, 'e', [Node(6, 'f'), Node(7, 'g'), Node(8, 'h')]),
Node(9, 'i')
]
def _get_choices(nodes, depth=0):
if not nodes:
return []
for node in nodes:
yield (node.ident, f"{depth * '-'}{node.value}")
yield from _get_choices(node.children, depth 1)
def get_choices():
return list(_get_choices(data))
print(result := get_choices())
for __, x in result:
print(x)
結果:
[(1, 'a'), (2, '-b'), (3, '-c'), (4, '--d'), (5, 'e'), (6, '-f'), (7, '-g'), (8, '-h'), (9, 'i')]
a
-b
-c
--d
e
-f
-g
-h
i
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395343.html
