我对编程有点缺乏经验,对return函数的工作方式有点困惑。我试图编写一个程序,将函数映射到嵌套列表的元素上。变量levels表示列表中嵌套级别的次数。我现在可以通过打印我的最终映射列表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的东西,但是我不知道怎么做。每次我尝试返回它,它只返回一个空列表或列表的一部分。我觉得我已经尝试了我能想到的每种回报配置。在
这将起作用:
或者稍微整洁一点的解决方案:
^{pr2}$这是递归地对层次结构中的每个列表应用
map_nested
方法。当递归到达列表中的元素时,它将应用原始调用中提供的函数。在注意,这适用于任意深度嵌套的列表,也适用于不平衡的嵌套列表(例如,
[1, 2, [3, 4]]
)。在我会用
totlist
作为一个参数:现在:
^{pr2}$如果要简化(而不是手动传递级别)并在执行过程中展平嵌套,请执行以下操作:
会给出:
相关问题 更多 >
编程相关推荐