python - 从Python中的递归函数返回

标签 python list recursion mapping return

我对编程有点缺乏经验,而且我对返回函数的工作原理有点困惑。我正在尝试编写一个程序,将函数映射到嵌套列表的元素上。变量级别表示列表中嵌套级别的次数。我目前可以通过打印我的最终映射列表 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]])。

关于python - 从Python中的递归函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21866927/

相关文章:

PHP:如何在数组中填充目录结构

c# - 使用 EWS 查找收件箱文件夹的所有子文件夹

python - 在python中将字符串转换为日期时间对象

python - 如何对以下元组列表进行唯一组合

java : list that contains unique elements in order

Java:如何初始化一个固定长度的List of List?

python - 使用线程控制 wxPython 中的 UI 元素

python - 尽管迁移已成功完成,但 Admin 或 Api 没有发生任何更改

r - 在 R 中创建一个衡量增长率差异的矩阵列表

javascript - 无法使用 JS 函数生成树