路径刷新算法

def find_paths_and_modify(data, target_path, new_value):
    paths = []
    stack = [([], data)]

    while stack:
        current_path, current_data = stack.pop()

        if isinstance(current_data, dict):
            for key, value in current_data.items():
                new_path = current_path + [key]
                stack.append((new_path, value))
        elif isinstance(current_data, list):
            for index, item in enumerate(current_data):
                new_path = current_path + [index]
                stack.append((new_path, item))
        else:
            paths.append(current_path)
            # Check if the current path matches the target path
            if current_path == target_path:
                current_dict = data
                for key in current_path[:-1]:
                    current_dict = current_dict[key]
                current_dict[current_path[-1]] = new_value

    return paths, data

# 假设你的字典存储在变量 'dict2' 中
dict2 = {
    "context": {
        "band": {
            "ccMap": 1,
            "ccs": [
                {
                    "bwp": {
                        "size": 50,
                        "start": 0
                    },
                    "chan": "NR_PUSCH",
                    "mod": "TYPE_64QAM",
                    "rb": {
                        "offset": 0,
                        "size": 10
                    }
                },
                {
                    "bwp": {
                        "size": 50,
                        "start": 0
                    },
                    "chan": "NR_PUSCH",
                    "mod": "TYPE_64QAM",
                    "rb": {
                        "offset": 0,
                        "size": 10
                    }
                }
            ]
        }
    }
}

target_path = ["context", "band", "ccs", 0, "bwp", "size"]  # 设置目标路径
new_value = 100  # 设置新的值

paths_list, modified_dict = find_paths_and_modify(dict2, target_path, new_value)

# 打印输出的路径
for path in paths_list:
    print(path)

# 打印修改后的字典
print(modified_dict)

posted @ 2024-01-16 23:40  岁叶年华  阅读(26)  评论(0)    收藏  举报