【问题标题】:TypeError: Reduce() of empty sequence with no initial valueTypeError:没有初始值的空序列的Reduce()
【发布时间】:2015-04-11 10:07:32
【问题描述】:

我目前正在尝试编写一个函数,它将给我一个元组,其 0 索引是该文件中的行数,其 1 索引是该文件中有多少个字符。到目前为止,我有一个元组列表,如下所示:

mapped = [(1, 50), (1, 11), (1, 58)]

我要写的那行是这样的:

reduce(lambda x:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))

如果它工作正常,那么它应该返回一个 (3, 119) 的元组。但是,我收到了

的错误
TypeError: reduce() of empty sequence with no initial value

谁能弄清楚这是为什么?

【问题讨论】:

  • 无法重现(Python 3.4.2)
  • 当您尝试减少空地图时也会出现此错误。

标签: python python-3.x tuples reduce


【解决方案1】:

没有人回答为什么会出现错误: TypeError: reduce() of empty sequence with no initial value

当第二个参数的列表文字为空时,会发生错误。所以如果你尝试 reduce(lambda x, y:(x[0]+y[0], x[1]+y[1]), [])

你会得到错误。

【讨论】:

    【解决方案2】:

    map(sum, ...) 更适合,看起来很漂亮。

    map(sum, zip(*mapped))
    

    如果列表的长度不同,您可以使用itertools.izip_longest

    【讨论】:

      【解决方案3】:

      这样使用:

      >>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),[i for i in mapped])
      (3, 119)
      >>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
      (3, 119)
      

      你错过的是 lambda 应该带两个参数,你只给一个。

      对于 Python3.x,请参见以下代码:

      >>> from functools import reduce
      >>> reduce(lambda x:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: <lambda>() takes exactly 1 positional argument (2 given)
      >>> reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
      (3, 119)
      

      【讨论】:

        【解决方案4】:
        reduce(lambda x,y:(x[0]+y[0], x[1]+y[1]),(i for i in mapped))
        

        这可能就是您想要的,或者至少这就是您所期望的输出;你必须在 lambda 表达式中添加,y 来告诉它会有两个参数。

        【讨论】:

          【解决方案5】:

          该函数需要在列表中至少有一个元素。 试试看:

          reduce(lambda x, y:(x[0]+y[0], x[1]+y[1]), [(0, 0)]+[i for i in mapped])
          

          在 [i for i in mapped] 为空的情况下 [(0, 0)] 是否强制返回至少 [(0, 0)]。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-04-20
            • 1970-01-01
            • 2015-09-05
            • 1970-01-01
            • 1970-01-01
            • 2018-12-31
            • 2015-03-11
            相关资源
            最近更新 更多