Nesting a string inside a list n times, i.e. List list list

def nest(x, n):
    a = []
    for i in range(n):
        a.append([x])
    return a

print nest("hello", 5)

It gives a way out

[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

Desired Result:

[[[[["hello"]]]]]
+4
source share
3 answers

Each rotation in a loop that you add to the list. You want to nest the list even more than add more material to it. You could do it something like this:

def nest(x, n):
    for _ in range(n):
        x = [x]
    return x

Each rotation in the loop xcontains a different list wrapped around it.

+5
source

instead of adding you, you can wrap xand call the method recursively until the call number is lessn

def nest(x, n):
    if n <= 0:
        return x
    else:
        return [nest(x, n-1)]
+2
source

pythonic recursion:

In [8]: def nest(x, n):
   ...:     return nest([x], n-1) if n else x 

DEMO:

In [9]: nest(3, 4)
Out[9]: [[[[3]]]]

In [11]: nest("Stackoverflow", 7)
Out[11]: [[[[[[['Stackoverflow']]]]]]]
+1

Source: https://habr.com/ru/post/1657967/


All Articles