繁体   English   中英

将嵌套的元组列表转换为元组中第一个元素的嵌套列表

[英]Converting nested list of tuples to nested list of first element from tuples

我有一个像这样的嵌套列表:

a = [([('m', 2), ([('o', 1), ([('k', 1), ('h', 1)], 2)], 3)], 5),
     ([('e', 3), ([([('t', 1), ('a', 1)], 2), (' ', 2)], 4)], 7)]

我想摆脱每个元组中的第二个元素,因此列表只会成为字符列表。 像那样:

[['m', ['o', ['k', 'h']]], ['e', [['t', 'a'], ' ']]]

我尝试过以下方法:

def transform(array):
    for x in array:
        if type(x[0]) is list:
            transform(x[0])
        else:
            x = x[0]

它将元组转换为字符,但它不会影响给定的数组

使用递归列表理解:

def recursive_strip(my_list):
    """Recursively remove the second element from nested lists of tuples."""
    return [
        recursive_strip(one) if isinstance(one, list) else one
        for one, two in my_list
    ]

在示例上运行此代码,我们得到:

a = [([('m', 2), ([('o', 1), ([('k', 1), ('h', 1)], 2)], 3)], 5),
     ([('e', 3), ([([('t', 1), ('a', 1)], 2), (' ', 2)], 4)], 7)]

result = recursive_strip(a)

result是:

[['m', ['o', ['k', 'h']]], ['e', [['t', 'a'], ' ']]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM