【问题标题】:Using encapsulated Lambda functions in Python to calculate the sum of lists在 Python 中使用封装的 Lambda 函数计算列表的总和
【发布时间】:2018-06-05 21:25:35
【问题描述】:

所以我尝试了这个

z=0
x = [2, 3, 4]
y = [4, 5]
t = map(lambda v : map(lambda w : v + w, y), x)
# t == [[6, 7], [7, 8], [8, 9]]
z = sum(t, [])

我们的循环遍历 x 和 y 并将值的总和添加到 z。由于某种原因,我得到了错误:

TypeError: can only concatenate list (not "map") to list

有什么想法吗?

【问题讨论】:

    标签: python python-3.x dictionary lambda map-function


    【解决方案1】:

    函数map 返回一个map object,而不是一个列表。函数sum 需要一个列表序列。您应该将地图对象转换为列表:

    t = map(lambda v : list(map(lambda w : v + w, y)), x)
    z = sum(t, [])
    #[6, 7, 7, 8, 8, 9]
    

    【讨论】:

      【解决方案2】:

      作为更易读、更高效的替代方案,您可以使用itertools.chain:

      from itertools import chain
      
      t = [[6, 7], [7, 8], [8, 9]]
      
      res = list(chain.from_iterable(t))
      
      print(res)
      
      [6, 7, 7, 8, 8, 9]
      

      【讨论】:

        猜你喜欢
        • 2011-09-04
        • 1970-01-01
        • 2012-10-03
        • 2018-09-04
        • 1970-01-01
        • 2014-09-22
        • 2021-04-12
        • 1970-01-01
        • 2015-07-12
        相关资源
        最近更新 更多