You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将递归Lambda列表修剪函数转换为常规def函数?

Converting the Lambda-based Prune Function to a Regular def Function

Got it, let's break this down step by step so you can see exactly how to translate that lambda into a working def function, and why your initial attempt didn't work.

First, let's clarify what the original lambda is doing:

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

This one-liner is a recursive list comprehension that:

  1. Iterates over every branch in the input tree
  2. Skips any branch that's an empty list ([])
  3. Recursively runs prune on every non-empty branch
  4. Collects all the processed branches into a new list and returns it

The Problem with Your Initial Code

Your function has two key issues:

  • You're not collecting the results of the recursive calls into a list (you just run prune(branch) without saving it anywhere)
  • You end up returning a single branch (the last one in your loop) instead of a list of all processed branches

Correct Translations

There are two straightforward ways to write this as a regular function:

Option 1: Direct List Comprehension (Most Similar to the Lambda)

This is almost identical to the lambda, just wrapped in a def block:

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

Option 2: Explicit Loop (More Verbose, Easier to Trace)

If you prefer to use a for loop instead of a list comprehension for clarity, this version does the exact same thing:

def prune(tree):
    pruned_results = []
    for branch in tree:
        # Only process non-empty branches
        if branch != []:
            # Recursively prune the branch and add it to our results
            pruned_results.append(prune(branch))
    # Return the fully pruned list
    return pruned_results

Testing It Out

Using your test list l = [[[[], []], [[], []]], [[], [], []]], running print(prune(l)) will output:

[[[], []], []]

Which matches the behavior of the original lambda perfectly.

内容的提问来源于stack exchange,提问作者math greg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:03