简体   繁体   中英

How do I transform this lambda function into def format?

I found this answer to a question here ( How to build a recursion for arbitrary lists? ) but I haven't learnt how to use lambdas .

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

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

I checked many websites but I can not seem to manage to transform this into a regular function like:

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

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

Can someone tell me what are those big square brackets for before prune and at the end?

All you have to do is slap a return on the front.

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

If you wanted to decompose the list comprehension —and there's no real reason to—it'd be:

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

Or:

def prune(tree):
    branches = []

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

    return branches

lambdas are always easily transform-able into a def with a single return statement:

f = lambda a: b

is always almost identical to

def f(a):
    return b

If you need to do your example without list comprehension:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM