簡體   English   中英

從python中的遞歸函數返回

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM