从python中的递归函数返回

时间:2014-02-18 22:33:16

标签: 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的东西,但我无法弄清楚如何做到这一点。每当我尝试返回它时,它只返回一个空列表或列表的一部分。我觉得我已经尝试过我能想到的各种回报配置。

2 个答案:

答案 0 :(得分:2)

这将有效:

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]])。

答案 1 :(得分:0)

我会让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]