代码之家  ›  专栏  ›  技术社区  ›  Johan Klemantan

带条件的嵌套循环中的lambda

  •  2
  • Johan Klemantan  · 技术社区  · 2 年前

    我在一次申请新工作的测试中遇到了这个问题。

    给定此阵列:

    arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]

    1. 对于列表中的每个元素,如果发现负值,我们希望将其排除在外
    2. 平方剩余值

    我已经用普通循环回答了

    for i in arr:
        for j in range(len(i)):
            if i[j]>0:
                asd = i[j]**2
                i[j] = asd
            else:
                i.remove(i[j])
    print(arr)
    

    [[1, 4, 36], [9, 16]]

    问题是,我必须使用 函数来传递问题。

    我尝试使用嵌套循环和lambda的条件,但这非常令人困惑。你知道怎么解决这个问题吗?任何帮助都将不胜感激。

    4 回复  |  直到 2 年前
        1
  •  3
  •   mozway    2 年前

    作为你 需要使用lambda

    [[x**2 for x in l if x>=0] for l in arr]
    

    转化为功能变体:

    list(map(lambda l: list(map(lambda x: x**2, filter(lambda x: x>=0, l))), arr))
    

    更长、效率更低、更神秘,但你确实有很多lambda;)

    输出: [[1, 4, 36], [9, 16]]

    list comprehension vs lambda+ filter

        2
  •  1
  •   SIGHUP    2 年前

    使用列表理解怎么样?

    list_ = [[-1, 1, 2, -2, 6], [3, 4, -5]]
    
    result = [[n*n for n in e if n >= 0] for e in list_]
    
    print(result)
    

    输出:

    [[1, 4, 36], [9, 16]]
    
        3
  •  0
  •   Ali Rn    2 年前

    lambda

    arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
    
    result = lambda nested_list: [[a ** 2 for a in b if a > 0] for b in nested_list]
    
    print(result(arr))
    
    >>> [[1, 4, 36], [9, 16]]
    
        4
  •  0
  •   cards    2 年前

    更详细一点:the partial 不是必需的,但分配是一种不好的做法 lambda

    from functools import partial
    
    power_2 = (2).__rpow__
    is_positive = (0).__lt__
    
    apply_to_row = partial(lambda row: list(map(power_2, filter(is_positive, row))))
    out = list(map(apply_to_row, arr))
    

    out = list(map(lambda row: list(map(power_2, filter(is_positive, row))), arr))
    
        5
  •  0
  •   sahasrara62    2 年前

    lambda

    >>> arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
    >>> function = lambda x: map(lambda j:j**2, filter(lambda y: y>0, x))
    >>> result = list(map(lambda x: list(function(x)), arr))
    >>> result
    [[1, 4, 36], [9, 16]]