【问题标题】:Finding paths in a json tree in python在python中的json树中查找路径
【发布时间】: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))
  • 你应该在问题中包含你得到的输出。

标签: python json


【解决方案1】:

您的代码有几个问题,但您得到的“错误”不是错误;它是path(tree, 0) 返回的值,它是一个生成器。您需要将其包装在 list() 中以强制它自行评估。也就是说,如果你这样做,你会遇到几个错误。即使你修复了表面错误,你的代码也不会给你想要的结果。

这段代码会做你想做的事:

import pprint


def paths(tree):
    if not tree['children']:
        yield (tree['id'],)
    else:
        for child in tree['children']:
            for descendant in paths(child):
                yield (tree['id'],) + descendant

tree = {
    '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': [
            {'reply': 0, 'id': 600, 'children': []},
            {'reply': 0, 'id': 700, 'children': []},
            {'reply': 0, 'id': 800, 'children': []},
            {'reply': 0, 'id': 900, 'children': []},
        ]}
        ]
    }

pprint.pprint(list(paths(tree)))

输出:

[(30, 451),
 (30, 307),
 (30, 276),
 (30, 253, 600),
 (30, 253, 700),
 (30, 253, 800),
 (30, 253, 900)]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多