【问题标题】:How to get the square of elements in list of lists using map? [duplicate]如何使用地图获取列表列表中元素的平方? [复制]
【发布时间】:2022-01-24 12:22:17
【问题描述】:

考虑以下列表:

arr = [[1, 2, 3], [3, 2, 1]]

我想得到它的平方,使用 maplambda 函数。结果应该是:

arr = [[1, 4, 9], [9, 4, 1]]

我试过这个:

print(list(map(lambda x: [lst**2 for lsts in arr for lst in lsts], arr)))

但我得到了答案:

[[1, 4, 9, 9, 4, 1], [1, 4, 9, 9, 4, 1]]

【问题讨论】:

  • map 已经为您提供了比arr 多一级的迭代。只需更改 lambda 以迭代内部级别:lambda x: [num**2 for num in x]...
  • 您也可以将当前lambda的内容修改为独立的理解:print([[num**2 for num in lst] for lst in arr]),不需要map
  • 哦,好吧,所以理解中的理解将在列表列表中迭代并返回相同的结构作为结果?有趣
  • 你也可以使用map两次:arr = list(map(lambda sub: list(map(lambda x: x**2, sub)), arr))
  • map两次看起来不太干净,我认为嵌套理解或map+comprehension更干净。

标签: python list


【解决方案1】:

试试这个:

arr = list(map(lambda List: [x**2 for x in List], arr))
# Output : [[1, 4, 9], [9, 4, 1]]

您还可以使用嵌套映射:

arr = list(map(lambda List: list(map(lambda x: x**2, List)), arr))
# or
square = lambda x: x**2
arr = list(map(lambda List: list(map(square, List)), arr))

【讨论】:

    【解决方案2】:

    类似这样的:

    arr = [[1,2,3],[3,2,1]]
    output = list(map(lambda x: [i**2 for i in x], arr))
    print(output)
    

    【讨论】:

      【解决方案3】:

      这结合了lambdas 和列表理解:

      arr = [[1, 2, 3], [4, 5, 6]]
      
      print(list(map(lambda x: [i * i for i in x], arr)))
      

      输出:

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

      【讨论】:

        【解决方案4】:

        考虑使用 numpy:

        arr = [[1,2,3],[3,2,1]]
        
        arr_numpy = np.array(arr)
        
        result = arr_numpy ** 2
        

        【讨论】:

        • 我知道 numpy,我想要地图,但谢谢
        • @w_sz 在这里学到了一些新东西,谢谢
        【解决方案5】:

        您提到您想使用 maplambda 但作为参考,您可以仅使用列表推导来做到这一点,

        [[y * y for y in x] for x in arr]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-01-13
          • 2014-12-16
          • 2022-07-09
          • 2014-12-01
          • 1970-01-01
          • 2021-05-19
          • 2022-01-22
          相关资源
          最近更新 更多