面试题答案
一键面试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
函数,它递归地遍历嵌套的字典和列表,为每个元素添加调试信息。
- 对于字典:
- 遍历字典的键值对,将路径更新为当前键,并递归处理值。
- 新的字典以更新后的路径作为键,递归处理后的结果作为值。
- 对于列表:
- 遍历列表的每个元素,将路径更新为当前索引,并递归处理元素。
- 新的列表包含递归处理后的元素。
- 对于其他类型(基本数据类型):
- 创建一个包含值、用途(这里设为未知)和来源(路径)的字典。
最后,调用 add_debug_info
函数处理原始数据,并输出添加调试信息后的结果。