Если я правильно понял ваш вопрос, то один из подходов к его решению - использование возврата. Вы можете рекурсивно искать элемент во вложенных списках, отслеживая при этом индексы. Когда элемент найден, вы возвращаетесь из функции. Вот код для подхода
_list1 = [
't',
[
'q',
['d',1],
['p',7],
[
'e',
['i',1],
['r',5]
]
],
[
'i',
['o',5],
['y',3],
['f',8]
]
]
_list2 = [
1,
2,
't',
['y',3]
]
def find_ind_rec(current_list, indexes, search_key):
for index,element in enumerate(current_list): # Iterate through the list
if element == search_key: # If element equals to the search_key, return True
indexes.append(index) # Add current index
return True
elif isinstance(element,list): # If element is another list (nested list), recursively search for search_key
indexes.append(index) # Add current index
if find_ind_rec(element,indexes,search_key): # If search_key found in this nested list, return true
return True
# Otherwise, backtrack!
indexes.pop()
return False # If search_key not found, return False
indexes = [] # Initially empty
find_ind_rec(_list1,indexes,['y',3]) # Search ['y',3] in example _list1
print(indexes)
indexes = [] # Initially empty
find_ind_rec(_list1,indexes,['i',1]) # Search ['i',1] in example _list1
print(indexes)
indexes = [] # Initially empty
find_ind_rec(_list2,indexes,3) # Search 3 in example _list2
print(indexes)
indexes = [] # Initially empty
find_ind_rec(_list2,indexes,5) # Search 5 in example _list2 --> Not found
print(indexes)
Вывод
[2, 2]
[1, 3, 1]
[3, 1]
[]