我正在解析JSON,并尝试基于“父母”键递归地创建树,但仍在努力获取期望的输出。这是JSON:

{
    "cases": [
        {
            "name": "A",
            "parents": [
                "E",
                "B"
            ]
        },
        {
            "name": "B",
            "parents": [
                "C",
                "D"
            ]
        },
                {
            "name": "C",
            "parents": [
                "E"
            ]
        },
        {
            "name": "D",
            "parents": [
                "E"
            ]
        },
        {
            "name": "E",
            "parents": [
            ]
        }
    ]
}


这是我的代码:

import json
import copy
FILE="somefile.json"

def find_path(test_name, data, current_steps):
    tc = return_test_data(test_name, data)
    parents = tc.get('parents', [])
    if not current_steps:
        current_steps.append(test_name)
    if not parents:
        return current_steps
    else:
        temp_steps = []
        for step in parents:
            new_c_s = copy.deepcopy(current_steps)
            new_c_s.append(step)
            new_steps = find_path(step, data, new_c_s)
            temp_steps.append(new_steps)
        return temp_steps


def return_test_data(test_name, data):
    for test in data['cases']:
        if test['name'] == test_name:
            return test

    return False


if __name__ == "__main__":
    data = json.load(open(FILE))

    steps = find_path("A", data, [])
    print ("Steps: {}".format(steps))


我希望能看到按其排列顺序排列的父母名单:

Steps: ['A', 'E', 'B', 'C', 'E', 'D', 'E']


在这种情况下,A有两个父母:E&B。对两个父母进行迭代,得到的结果是:

['A', 'E', {parents of E}, 'B', {parents of B}].


因为E没有父母,而B有C和D的父母,所以(在我看来)变为:

['A', 'E', 'B', 'C', {parents of C}', 'D', {parents of D}]


最终变为:

['A', 'E', 'B', 'C', 'E', 'D', 'E']


相反,我得到:

Steps: [['A', 'E'], [[['A', 'B', 'C', 'E']], [['A', 'B', 'D', 'E']]]]


我确定我递归过多,但是无法确切知道是什么。

最佳答案

看来您使每个步骤都变得比必要的要复杂一些。我相信这会产生您想要的信息:

import json

FILE = "somefile.json"

def find_path(test_name, data):

    dictionary = return_test_data(test_name, data)

    if dictionary:
        current_steps = [test_name]

        if 'parents' in dictionary:
            for parent in dictionary['parents']:
                current_steps.extend(find_path(parent, data))

        return current_steps

    return None

def return_test_data(name, data):
    for dictionary in data['cases']:
        if dictionary['name'] == name:
            return dictionary

    return None

if __name__ == "__main__":
    data = json.load(open(FILE))

    steps = find_path("A", data)

    print("Steps:", steps)


输出值

> python3 test.py
Steps: ['A', 'E', 'B', 'C', 'E', 'D', 'E']
>

关于python - 递归遍历列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48942587/

10-16 23:27