簡體   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