简体   繁体   English

Python:如何制作深度为n的嵌套列表?

[英]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.

相关问题 具有深度值的镜像列表,到嵌套列表 ~ Python - Mirroring List with Depth Values, to Nested List ~ Python Python 注释的类型,用于未定义嵌套列表深度的嵌套列表 - Python annotation's type for nested list with undefined nested list depth 如何进行嵌套列表理解(Python) - How to make a nested list comprehension (Python) 如何使用python避免嵌套函数中的深度递归 - How to avoid depth recursion in nested functions with python 如何通过\ n拆分嵌套列表但跳过第一个?蟒蛇 - How to split a nested list by \n but skip the the first one? Python 如何在 Plotly/Python 中制作“市场深度”图表? - How to make "Market Depth" chart in Plotly/Python? 如何在Python的嵌套字典中检索嵌套字典的深度? - How to retrieve the depth of nested dictionaries in nested dictionaries in Python? 如何在Python中制作n个数字的列表并随机选择任何数字? - How to make a list of n numbers in Python and randomly select any number? 如何在 Python 中有效地从 n 元素集的列表中制作 n+1 元素集的列表? - How do I make a list of sets of n+1 elements out of a list of sets of n elements efficiently in Python? Python:如何循环不同深度的列表列表? - Python: How to loop a list of lists of varying depth?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM