反转嵌套列表以及 python 中的元素
Reverse a nested list along with the elements in python
我有以下列表:
lst = ['123', '456', [['123', '456']], ['123', '456']]
我想反转列表,每个列表的元素也以相反的顺序排列。输出应如下所示:
lst = [['654', '321'], [['654', '321']], '654', '321']
def recursive_reverse(x):
if isinstance(x, str):
return x[::-1]
if isinstance(x, list):
return [recursive_reverse(i) for i in x][::-1]
return x
lst = ["123", "456", [["123", "456"], "hello"], ["123", "456"]]
print(recursive_reverse(lst))
打印出来
[['654', '321'], ['olleh', ['654', '321']], '654', '321']
我有以下列表:
lst = ['123', '456', [['123', '456']], ['123', '456']]
我想反转列表,每个列表的元素也以相反的顺序排列。输出应如下所示:
lst = [['654', '321'], [['654', '321']], '654', '321']
def recursive_reverse(x):
if isinstance(x, str):
return x[::-1]
if isinstance(x, list):
return [recursive_reverse(i) for i in x][::-1]
return x
lst = ["123", "456", [["123", "456"], "hello"], ["123", "456"]]
print(recursive_reverse(lst))
打印出来
[['654', '321'], ['olleh', ['654', '321']], '654', '321']