如何将此lambda函数转换为def格式? [英] How do I transform this lambda function into def format?

查看:154
本文介绍了如何将此lambda函数转换为def格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解这段代码的细节:



I am trying to understand the details of this code do:

 prune = lambda tree : [prune(branch) for branch in tree if branch != []]

l = [[[[], []], [[], []]], [[], [], []]]
prune(l)





但是我还没有学过lambda函数。



我尝试过:



我试图将其分解为def函数格式





But i have not yet learnt the lambda function.

What I have tried:

I am trying to break it down to the def function format

def prune(tree):
    for branch in tree:
        if branch!=[]:
             prune(branch)
    return branch
print prune([[[[], []], [[], []]], [[], [], []]])





但它没有给出相同的结果,我做错了什么?



But it doesn't give the same result, what am I doing wrong?

推荐答案

def prune(tree):
    result = []
    for branch in tree:
        if branch != []:
            result.append(prune(branch))
    return result



你几乎就在那里;你错过的唯一一步是将元素添加到结果列表中。


You were almost there; the only step you missed, was adding the elements to a result list.


这篇关于如何将此lambda函数转换为def格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆