Boa*_*Boa 4 python nested list python-2.7
def nest(x, n):
a = []
for i in range(n):
a.append([x])
return a
print nest("hello", 5)
Run Code Online (Sandbox Code Playgroud)
这给出了输出
[['hello'], ['hello'], ['hello'], ['hello'], ['hello']]
Run Code Online (Sandbox Code Playgroud)
期望的输出是
[[[[["hello"]]]]]
Run Code Online (Sandbox Code Playgroud)
每次转弯都要添加到列表中.您希望进一步嵌套列表,而不是在其上添加更多内容.你可以这样做:
def nest(x, n):
for _ in range(n):
x = [x]
return x
Run Code Online (Sandbox Code Playgroud)
每次转过循环,都会x有另一个列表.