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

求职技术测试题:使用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 original arr. 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 where x > 0).
  • Inner map(): Takes the filtered positive numbers and applies the lambda to square each one.
  • Convert to lists: Since map() and filter() return iterators in Python 3, we wrap them in list() 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 20:03:10