我有一组字符串和嵌套在列表中的嵌套字符串列表。
list1 = ['abc','def',[['abc','def']],['abc','def']].
我想得到类似如下所示的输出:
[['fed','cba'], [['fed','cba']], 'fed', 'cba']
当我使用内置 reverse() 方法和 [::-1] 的传统方法时。如下图:
list1 = ['abc', 'def', [['abc', 'def']], ['abc', 'def']]
[x[::-1] for x in list1][::-1]
# and got output as [['def', 'abc'], [['abc', 'def']], 'fed', 'cba']
请给我解释一下?
最佳答案
您的问题是您需要反转主列表、此列表中的每个子列表以及您在途中遇到的每个字符串。您需要一些更通用的方法,可能使用递归:
def deep_reverse(x):
if isinstance(x, list):
x = [deep_reverse(subx) for subx in x] # reverse every element
x = x[::-1] # reverse the list itself
elif isinstance(x, str):
x = x[::-1]
return x
list1 = ['abc','def',[['abc','def']],['abc','def']]
reversed_list1 = deep_reverse(list1)
# [['fed', 'cba'], [['fed', 'cba']], 'fed', 'cba']
https://stackoverflow.com/questions/67899721/