求职技术测试题:使用Lambda函数实现带条件的嵌套数组处理
Great question! First, let's note that your original loop code has a bug—when you remove elements from a list while iterating over its indices, you'll end up with index errors or skip elements (since the list length changes mid-loop). For example, running your code will throw an IndexError because after removing elements, the list becomes shorter than the original range you're iterating over.
Now, to solve this with lambda functions, we can combine Python's map() and filter() higher-order functions, which work perfectly with lambdas for this kind of data transformation. Here's how you can do it:
arr = [[-1, 1, 2, -2, 6], [3, 4, -5]] processed_arr = list(map( lambda sublist: list(map( lambda num: num ** 2, filter(lambda x: x > 0, sublist) )), arr )) print(processed_arr) # Output: [[1, 4, 36], [9, 16]]
Let's break this down step by step:
- Outer
map(): Iterates over each sublist in the originalarr. The outer lambda takes each sublist as input. - Inner
filter(): For each sublist, we first filter out any numbers that are not positive (i.e., keep only values wherex > 0). - Inner
map(): Takes the filtered positive numbers and applies the lambda to square each one. - Convert to lists: Since
map()andfilter()return iterators in Python 3, we wrap them inlist()to get the final nested list structure matching your expected output.
This approach avoids the pitfalls of your original loop and strictly uses lambda functions as required, producing exactly the result you need.
内容的提问来源于stack exchange,提问作者Johan Klemantan

