我对编程有点不熟悉,并且对返回函数的工作原理有些困惑。我正在尝试编写一个将函数映射到嵌套列表的元素的程序。变量级别表示列表中嵌套级别的次数。目前,我可以得到程序通过打印我的最终映射列表,totlist工作:从Python中的递归函数返回
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,但我无法弄清楚如何做到这一点。每次我尝试返回它时,它都会返回一个空列表或列表的一部分。我觉得我已经尝试了我能想到的每种回报配置。
是否尝试用'''return totlist'''替换'''print(totlist)''? – bj0
我做到了。它重新调整了[] – Beth
你说它打印正确,如果你真的做了替换,它将返回它正在打印的内容。您必须记住将该返回值分配给呼叫站点上的变量并将其打印出来。 – bj0