【发布时间】:2015-08-20 07:54:32
【问题描述】:
我有一个表单的 json 树
{"reply": 0, "id": 30, "children": [{"reply": 0, "id": 451, "children": []}, {"reply": 0, "id": 307, "children": []}, {"reply": 0, "id": 276, "children": []}, {"reply": 0, "id": 253, "children": []}]}
我想获取从根到 json 树的叶子的所有路径。 为此,我正在使用
import json
f=open('tree_json','r')
def paths(tree, cur=()):
if not tree:
yield cur
else:
for n, s in tree.items():
for path in paths(s, cur+(n,)):
yield path
for line in f:
tree=json.loads(line)
print list(paths(tree,(0,)))
但是,我无法在树中打印路径。我想要的输出是: {30,451}、{30,307}、{30,276}。我得到了
for n, s in tree.items():
AttributeError: 'int' object has no attribute 'items'
【问题讨论】:
-
首先,不要在循环中定义函数。
-
其次,你想要什么输出,得到什么输出?
-
@cyphase :编辑了问题。错误是
-
这不是错误,这是
paths(tree,0)的返回值。试试print list(paths(tree,0))。 -
你应该在问题中包含你得到的输出。