[英]Python: how to make a nested list of depth n?
I want to make a list of list of list... of depth n. 我要列出深度为n的清单清单。
Curently, I use: 目前,我使用:
a = []
for i in range(n - 1):
a = [a]
print a
For example, if n = 3
i got [[[ ]]]
. 例如,如果n = 3
我得到[[[ ]]]
。
Is it a clearest and more pythonic way to do this? 这是最清晰,更Python化的方法吗?
Yes, I think you've already got the best way. 是的,我认为您已经有了最好的方法。 It's faster and doesn't suffer the limits mentioned by @Aleksi 它更快且不受@Aleksi提及的限制
Alternative would be to write a recursive function or use eval 替代方法是编写一个递归函数或使用eval
eval('['*n + ']'*n) # much slower than a for loop!
Is this Pythonic enough? 这足够Pythonic吗?
>>> n = 5
>>> map(lambda i: (lambda f, *a: f(f, [], *a))(lambda rec, k, i: k if i == 2 else rec(rec, [k], i-1), i), [n])
[[[[[]]]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.