递归迭代列表

时间:2018-02-23 06:47:11

标签: python recursion

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

我确定我递归过多地传递,但无法弄清楚到底是什么。

2 个答案:

答案 0 :(得分:1)

你可以像这样迭代结构:

代码:

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']

答案 1 :(得分:1)

看起来你已经使每一步都比必要的复杂一点。我相信这会产生你想要的信息:

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']
>