如何反转python中嵌套列表中的字符串列表?

我有一组字符串和嵌套在列表中的字符串嵌套列表。

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']


以上是如何反转python中嵌套列表中的字符串列表?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>