У меня есть набор данных словарей Python, которые содержат как списки, так и словари, которые также содержат списки и словари.
Я хочу найти все экземпляры подстроки в любом из значений и хочу знать путь, по которому я ее нашел. Я приведу упрощенный пример:
Код: Выделить всё
[
{
"name": "doug",
"foods": [ "cheese", "apple", "hotdog" ],
"address" : { "street": "1st", "house": "12345" },
},
{
"name": "alice",
"foods": ["carrot", "hamburger", "cookie"],
"address": { "street": "iceberg", "house": "5432" },
}
]
Код: Выделить всё
[
[0,"name","doug"],
[0,"foods","2","hotdog"]
]
И мои фактические данные немного сложнее. Я бы хотел, чтобы мой алгоритм работал с любыми произвольно вложенными списками и объектами.
Вот моя последняя попытка:
Код: Выделить всё
def recursive_search(space, hint):
if isinstance(space, int):
# I treat ints as str for matching purposes
space = str(space)
if isinstance(space, str):
# I've reached the end of the path
if hint in space:
# I found one!
return [ space ]
return None
if isinstance(space, list):
list_results = []
for index, item in enumerate(space):
result = recursive_search(item, hint )
if result is None:
continue
result.append(index)
list_results.append(result)
if len(list_results) > 0:
return list_results
return None
if isinstance(space, dict):
dict_results = []
for key, value in space.items():
result = recursive_search(value, hint )
if result is None:
continue
result.append(key)
dict_results.append(result)
if len(dict_results) > 0:
return dict_results
return None
return None
Это похоже на задачу из учебника с элегантным ответом, и я на это надеюсь.
Подробнее здесь: https://stackoverflow.com/questions/798 ... th-of-each
Мобильная версия