[英]Recursive function to nested lists
I have tried to crate a recursive function that gets a number and returns a list of nested list according to the index.我试图创建一个递归的 function,它获取一个数字并根据索引返回一个嵌套列表的列表。 For example, for 0, the function returns an empty list []
.例如,对于 0,function 返回一个空列表[]
。 for 1, the function returns [[], [[]]]
.对于 1,function 返回[[], [[]]]
。 for 3 the function returns [ [], [ [] ], [ [], [ [] ] ]]
, and so on.对于 3,function 返回[ [], [ [] ], [ [], [ [] ] ]]
等。
def func(n):
if n == 0:
return []
return [func(n-1)]
i have tried many different approaches for this problem.我已经尝试过很多不同的方法来解决这个问题。 I cant figure out how to extend my output to nested list according to the task.我不知道如何根据任务将我的 output 扩展到嵌套列表。
What I think you're looking for is something like this:我认为您正在寻找的是这样的东西:
def f(n):
L = []
for i in range(n):
L.append(f(i))
return L
My confusion stems from your examples.我的困惑源于你的例子。 For n=0
, there are 0 elements and for n=3
there are 3 elements, but there are 2 elements for n=1
.对于n=0
,有 0 个元素,对于n=3
有 3 个元素,但对于n=1
有 2 个元素。 This should work where n
is the number of elements in the final list这应该适用于n
是最终列表中元素的数量
Each list actually contains all the preceding lists, not just the immediately preceding list.每个列表实际上包含所有前面的列表,而不仅仅是前面的列表。 (Based on your example for func(3)
, your question seems to mistakenly refer to the list returned by func(2)
as the list returned by func(1)
.) (根据您的func(3)
示例,您的问题似乎错误地将func(2)
返回的列表称为func(1)
返回的列表。)
func(0) == []
func(1) == [func(0)] == [[]]
func(2) == [func(0), func(1)] == [[], [[]]]
func(3) == [func(0), func(1), func(2)] == [[] , [[]] , [[], [[]]]]
...
func(n) == [func(0), func(1), ..., func(n-1)]
This is basically a set-theoretic definition of the natural numbers, due to von Neumann.这基本上是自然数的集合论定义,归功于冯诺依曼。 Zero is define to be the empty set, and the successor of each number x
is the union of x
and the set containing x
:零被定义为空集,每个数字x
的后继是x
和包含x
的集合的并集:
0 == {}
1 == 0 | {0} == {} | {{}} == {{}}
2 == 1 | {1} == {{}} | {{{}}} == {{}, {{}}}
I leave it as an exercise to implement this using lists instead of sets.我把它留作练习,使用列表而不是集合来实现它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.