如何将递归Lambda列表修剪函数转换为常规def函数?
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:
- Iterates over every
branchin the inputtree - Skips any branch that's an empty list (
[]) - Recursively runs
pruneon every non-empty branch - 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

