Python 将一个字符串嵌套在一个列表中n次

Python 将一个字符串嵌套在一个列表中n次,python,list,python-2.7,nested,Python,List,Python 2.7,Nested,这将给出一个输出 def nest(x, n): a = [] for i in range(n): a.append([x]) return a print nest("hello", 5) 所需输出为 [['hello'], ['hello'], ['hello'], ['hello'], ['hello']] 您不需要追加,而是应该包装x并递归调用该方法,直到调用号小于n [[[[["hello"]]]]] def嵌套(x,n): 如果n通过

这将给出一个输出

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

print nest("hello", 5)
所需输出为

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

您不需要追加,而是应该包装
x
并递归调用该方法,直到调用号小于
n

[[[[["hello"]]]]]
def嵌套(x,n):

如果n通过循环的每一圈都添加到列表中。您希望进一步嵌套列表,而不是在列表中添加更多内容。你可以这样做:

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

循环中的每一圈,
x
都有另一个列表围绕着它。

这里是一个pythonic递归方法:

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


这个解决方案很有趣,但它使用递归,这是出了名的比循环慢。这种递归有好处吗?如果
n
是数值,但不是非负整数,则此解决方案也会进入无限循环——如果n是,也许您应该使用
——我已经编辑了代码。我很确定,对于较小的
n
来说,方法执行时间不会太长。我将此视为不同的方法,但我承认,
khelwood
解决方案似乎更好。我只是想说@m.antkowicz方法的“优点”是,它可以写在一行中,这看起来很酷,因此+1。虽然方法通常是better@jamylak我没有注意到m.antkowicz的答案是递归方法:-)。虽然它比它应该是的更复杂。关于凯尔伍德的方法,通常更好。
In [8]: def nest(x, n):
   ...:     return nest([x], n-1) if n else x 
In [9]: nest(3, 4)
Out[9]: [[[[3]]]]

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