Эта функция переворачивает все элементы, найденные в списке. Даже внутренние списки реверсируются. Моя проблема в том, что я не понимаю, как reversed_list сохраняет 7 и 6 после рекурсии. С тех пор, как называется Deep_Reverse, reversed_list становится пустым, а затем он сохраняет обратную сторону внутреннего списка, который составляет [5, 4, 3]. Что я не понимаю, так это то, что как только этот элемент будет добавлен, reversed_list становится [7, 6, [5, 4, 3]] < /p>
def deep_reverse(arr):
# Terminaiton / Base condition
if len(arr) < 1:
return arr
reversed_items = [] # final list to be returned
for item in arr[::-1]:
# If this item is a list itself, invoke deep_reverse to reverse the items recursively.
if type(item) is list:
item = deep_reverse(item)
# append the item to the final list
reversed_items.append(item)
print(reversed_items)
return reversed_items ```
deep_reverse([1, 2, [3, 4, 5], 6, 7])
#printing the reversed_list
[7]
[7, 6]
[5]
[5, 4]
[5, 4, 3]
[7, 6, [5, 4, 3]]
[7, 6, [5, 4, 3], 2]
[7, 6, [5, 4, 3], 2, 1]
Подробнее здесь: https://stackoverflow.com/questions/726 ... sive-loops