繁体   English   中英

递归遍历列表

[英]Recursively iterate over lists

我正在解析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']]]]

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

您可以像这样迭代结构:

码:

parents_list = []
for record in data:
    if record['name'] not in parents_list:
        parents_list.append(record['name'])
        for p in record['parents']:
            parents_list.append(p)

print(parents_list)

结果:

['A', 'E', 'B', 'C', 'E', '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)

OUTPUT

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM