下面是一个示例代码,使用递归搜索函数来返回一个对象:
def recursive_search(obj, target_key):
if isinstance(obj, dict): # 如果是字典类型
if target_key in obj: # 如果目标键存在
return obj[target_key]
else: # 否则继续搜索字典的值
for value in obj.values():
result = recursive_search(value, target_key)
if result is not None:
return result
elif isinstance(obj, list): # 如果是列表类型
for item in obj:
result = recursive_search(item, target_key)
if result is not None:
return result
return None # 如果找不到目标键,则返回None
# 示例字典
data = {
"key1": "value1",
"key2": "value2",
"key3": {
"inner_key1": "inner_value1",
"inner_key2": {
"inner_inner_key": "inner_inner_value"
}
},
"key4": [
{
"inner_key": "inner_value"
},
{
"inner_key": "target_value"
}
]
}
# 调用递归搜索函数
result = recursive_search(data, "target_key")
print(result) # 输出 "target_value"
在上面的示例代码中,recursive_search
函数接受两个参数:obj
是要搜索的对象,target_key
是要搜索的目标键。该函数首先检查 obj
的类型,如果是字典,则遍历字典的键值对,如果目标键存在,则返回对应的值;如果目标键不存在,则递归调用 recursive_search
函数来搜索字典的值。如果 obj
是列表类型,则遍历列表的元素,并递归调用 recursive_search
函数来搜索元素。如果找不到目标键,则返回 None
。
在示例代码中,我们使用了一个示例字典 data
,包含了嵌套的字典和列表。我们调用 recursive_search
函数来搜索目标键 "target_key"
,并将结果打印出来。结果为 "target_value"
。
下一篇:编写一个订单通知类Python