AndSolomin34
AndSolomin34

Reputation: 409

Converting nested list of tuples to nested list of first element from tuples

I have a nested list like this one:

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

I'd like to get rid of the second element in every tuple, so the list becomes a list of chars only. Like that:

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

I've tried the following:

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

It turns tuples to chars, but it doesn't affect the given array

Upvotes: 1

Views: 134

Answers (1)

Luca Cappelletti
Luca Cappelletti

Reputation: 2545

Using a recursive list comprehension:

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
    ]

Running this code on the example provided we get:

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)

With result being:

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

Upvotes: 3

Related Questions