Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition to nested list

I wanted to add element with the next value to the most nested list, i. e.

For list

list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]

The program should return

list_out = [2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

In case with e. x. two equal nests, I wanted to get:

list_in = [2, [4], [3]]

list_out = [2, [4, 5], [3, 4]]

How to do it?

like image 859
Malum Phobos Avatar asked Aug 12 '26 20:08

Malum Phobos


1 Answers

A recursive solution:

list_in = [2, 3, [4, 5, [6, 7], 6], 2, [5, 6]]


def get_depths(lst, depths, current_depth=0):
    out = [
        get_depths(v, depths, current_depth + 1) if isinstance(v, list) else v
        for v in lst
    ]
    depths.setdefault(current_depth, []).append(out)
    return out


depths = {}
list_out = get_depths(list_in, depths)
for lst in depths[max(depths)]:
    lst.append(lst[-1] + 1)

print(list_out)

Prints:

[2, 3, [4, 5, [6, 7, 8], 6], 2, [5, 6]]

For list_in = [2, [4], [3]] it prints:

[2, [4, 5], [3, 4]]
like image 95
Andrej Kesely Avatar answered Aug 15 '26 09:08

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!