MST

星途 面试题库

面试题:Python复杂数据结构变量的调试信息注入

假设有一个嵌套的Python字典数据结构 `data = {'key1': [1, 2, {'sub_key':'sub_value'}], 'key2': {'nested_key': 'nested_value'}}`,现在需要为这个字典的各个层级的元素添加详细的调试信息标签,以便在调试时清楚知道每个元素的用途和来源,你会如何实现?
33.3万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def add_debug_info(data, path=''):
    if isinstance(data, dict):
        new_dict = {}
        for key, value in data.items():
            new_key = f"{path}{'.' if path else ''}{key}"
            new_dict[new_key] = add_debug_info(value, new_key)
        return new_dict
    elif isinstance(data, list):
        new_list = []
        for index, item in enumerate(data):
            new_path = f"{path}[{index}]"
            new_list.append(add_debug_info(item, new_path))
        return new_list
    else:
        debug_info = {
            'value': data,
            'usage': 'Unknown usage',
           'source': f'Element at {path}'
        }
        return debug_info


data = {'key1': [1, 2, {'sub_key':'sub_value'}], 'key2': {'nested_key': 'nested_value'}}
result = add_debug_info(data)
print(result)

上述代码定义了一个 add_debug_info 函数,它递归地遍历嵌套的字典和列表,为每个元素添加调试信息。

  1. 对于字典
    • 遍历字典的键值对,将路径更新为当前键,并递归处理值。
    • 新的字典以更新后的路径作为键,递归处理后的结果作为值。
  2. 对于列表
    • 遍历列表的每个元素,将路径更新为当前索引,并递归处理元素。
    • 新的列表包含递归处理后的元素。
  3. 对于其他类型(基本数据类型)
    • 创建一个包含值、用途(这里设为未知)和来源(路径)的字典。

最后,调用 add_debug_info 函数处理原始数据,并输出添加调试信息后的结果。