首页 > 解决方案 > 如何将此 lambda 函数转换为 def 格式?

问题描述

我在这里找到了一个问题的答案(如何为任意列表构建递归?),但我还没有学会如何使用lambdas

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

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

我检查了许多网站,但似乎无法将其转换为常规功能,例如:

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

print prune([[[[], []], [[], []]], [[], [], []]])

有人能告诉我修剪之前和结尾的那些大方括号是什么吗?

标签: pythonpython-2.7function

解决方案


你所要做的就是return在前面拍一个耳光。

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

如果你想分解列表推导——并且没有真正的理由——那就是:

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

或者:

def prune(tree):
    branches = []

    for branch in tree:
        if branch != []:
            branches.append(prune(branch))

    return branches

推荐阅读