Start with empty list, create a list of size 3, and then add more values and create another list

Viewed 101

I have an expression inside a list:

l = [['h'], '+', ['c'], '-', ['d'], '+', [['e'], '-', ['f'], '+', ['y']], '+', ['a']]

I want to build an expression in a binary format by creating lists of size 3 until the entire original list has been iterated. This means that if any nested lists of lists exist, I have to traverse them as well. This would be the result:

final_list = [[[[['h'], '+', ['c']], '-', ['d']], '+', [[['e'], '-', ['f']], '+', ['y']]], '+', ['a']]

I have tried:

count = 0
def make_list(l):
    final_list = []
    temp_list = []
    for index, value in enumerate(l):
        count += 1
        if len(value) == 1 or (value == '+' or value == '-'):
            temp_list.append(value)
        elif len(value) != 1:
            final_list.append(make_list(l[index]))
        if count == 3:
            final_list.append(temp_list[:])
            temp_list.clear()
            count = 1
    return final_list

The problem with this code is that it adds new lists from temp_list, so the resulting answer is like this:

[[[[['h'], '+', ['c']], ['-', ['d']], '+', [[['e'], '-', ['f']], '+', ['y']], '+', ['a']]]

EDIT: MYousefi's solution works for any expression as long as it is not size 3. But when an expression of size 3 like this is inputted:

[['b'], '+', [['c'], '-', ['d'], '+', ['e']]]

Then his solution does not access and create a list of size 3 continuously inside the nested list.

1 Answers

Here's a recursive definition:

def make_list(l):
    if isinstance(l, str) or len(l) <= 3:
        return l
    return [make_list(l[:-2]), make_list(l[-2]), make_list(l[-1])]
Related