[英]returning from recursive function in python
我对编程没有经验,并且对返回函数的工作方式有些困惑。 我正在尝试编写一个将函数映射到嵌套列表的元素上的程序。 可变级别表示列表中存在嵌套级别的次数。 我目前可以通过打印最终的映射列表totlist来使程序正常工作:
def map_nested(listbasket, function, levels): #listbasket is the list that contains lists
totlist=[] #this list will store the list after the function has been mapped to it
for listelement in listbasket:
if levels<=2: #once we get to the level that just contains a list of lists
newlist=list(map(function,listelement))
totlist.append(newlist) #add to final mapped list
else:
map_nested(listelement, function, levels-1) #recursively call for next level
print(totlist)
map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3) # my test function
相反,我想要一些返回totlist的东西,但是我不知道该怎么做。 每当我尝试返回它时,它只会返回一个空列表或列表的一部分。 我觉得我已经尝试过我能想到的每种收益配置。
这将起作用:
import math
def map_nested(listbasket, function, levels): #listbasket is the list that contains lists
totlist=[] #this list will store the list after the function has been mapped to it
for listelement in listbasket:
if levels<=2: #once we get to the level that just contains a list of lists
newlist=list(map(function,listelement))
totlist.append(newlist) #add to final mapped list
else:
totlist.append(map_nested(listelement, function, levels-1))
return totlist
map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3) # my test function
或稍微整洁的解决方案:
import math
def map_nested(input, function):
if type(input) is list:
return [map_nested(e, function) for e in input]
else:
return function(input)
print map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt)
这是将map_nested
方法递归应用于层次结构中的每个列表。 当递归到达列表中的某个元素时,它将应用原始调用中提供的功能。
请注意,这适用于任意深度嵌套的列表,也适用于不平衡的嵌套列表(例如[1, 2, [3, 4]]
)。
我会totlist
一个论点:
def map_nested(listbasket, function, levels, totlist=None):
if totlist is None:
totlist = []
for listelement in listbasket:
if levels <= 2:
newlist = list(map(function, listelement))
totlist.append(newlist) #add to final mapped list
else:
map_nested(listelement, function, levels-1, totlist)
return totlist
现在:
>>> map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3)
[[1.0, 1.4142135623730951],
[1.7320508075688772, 2.0],
[2.23606797749979, 2.449489742783178],
[2.6457513110645907, 2.8284271247461903]]
如果您想简化(而不是手动传递关卡)并在移动时平整嵌套,例如:
def map_nested_2(lst, f, out=None):
if out is None:
out = []
for item in lst:
if isinstance(item, list):
map_nested_2(item, f, out)
else:
out.append(f(item))
return out
将给出:
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979,
2.449489742783178, 2.6457513110645907, 2.8284271247461903]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.