鑒于以下串列:
a = [
{'parent': 'p1', 'parent_name': 'pn1', 'child': 'c1', 'child_name': 'cn1'},
{'parent': 'p1', 'parent_name': 'pn1', 'child': 'c2', 'child_name': 'cn2'},
{'parent': 'c1', 'parent_name': 'cn1', 'child': 'c3', 'child_name': 'cn3'},
{'parent': 'c1', 'parent_name': 'cn1', 'child': 'c4', 'child_name': 'cn4'},
{'parent': 'c4', 'parent_name': 'cn4', 'child': 'c5', 'child_name': 'cn5'},
{'parent': 'c2', 'parent_name': 'cn2', 'child': 'c6', 'child_name': 'cn6'},
{'parent': 'c3', 'parent_name': 'cn3', 'child': 'c7', 'child_name': 'cn7'}
]
我想創建一個分層的串列字典到目前為止,我已經制作了運行良好的代碼,但由于某種原因,子 c3 和 c4 重復了兩次。我哪里做錯了?
def build(key):
children = [(item['child'], item['child_name']) for item in a if item['parent'] == key]
data = {}
for k, name in children:
data[k] = {'child': k, 'child_name': name, 'children': []}
for item in a:
if item['parent'] == k:
data[k]['children'].append(build(k))
return data
編輯: 上面的代碼產生這個輸出:
{'c1': {'child': 'c1',
'child_name': 'cn1',
'children': [{'c3': {'child': 'c3',
'child_name': 'cn3',
'children': [{'c7': {'child': 'c7',
'child_name': 'cn7',
'children': []}}]},
'c4': {'child': 'c4',
'child_name': 'cn4',
'children': [{'c5': {'child': 'c5',
'child_name': 'cn5',
'children': []}}]}},
{'c3': {'child': 'c3',
'child_name': 'cn3',
'children': [{'c7': {'child': 'c7',
'child_name': 'cn7',
'children': []}}]},
'c4': {'child': 'c4',
'child_name': 'cn4',
'children': [{'c5': {'child': 'c5',
'child_name': 'cn5',
'children': []}}]}}]},
'c2': {'child': 'c2',
'child_name': 'cn2',
'children': [{'c6': {'child': 'c6',
'child_name': 'cn6',
'children': []}}]}}
我需要完全相同的輸出,但顯然沒有重復(這里 c1 的孩子重復兩次)
uj5u.com熱心網友回復:
c3例如,由于下面的第 2 行而重復了兩次:
data[k] = {'child': k, 'child_name': name, 'children': []}
for item in a: # 'c3' will be found twice in a
if item['parent'] == k:
因為在 中c3出現兩次a,您將其子項添加兩次。
我不確定你為什么需要做那個回圈。對我來說,如果您洗掉該回圈并執行data[k]['children'].append(build(k))以下操作,它看起來會起作用data[k] = {'child': k, 'child_name': name, 'children': []}:
data[k] = {'child': k, 'child_name': name, 'children': []}
data[k]['children'].append(build(k))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/398744.html
上一篇:遞回正數求和程式
下一篇:遞回洗掉重復字符C
