【问题标题】:python - Length of a list with the reduce() functionpython - 使用reduce()函数的列表长度
【发布时间】:2017-05-31 12:58:44
【问题描述】:

我需要一些帮助来使用 reduce 函数计算列表中元素的数量。

def lenReduce(L):
  return reduce(lambda x: x + 1, L)

有了这个,我收到以下错误消息:

TypeError: <lambda>() takes 1 positional argument but 2 were given

来自柏林的问候。 ;-)

【问题讨论】:

    标签: python functional-programming reduce


    【解决方案1】:

    lenReduce([5,3,1])

    返回7

    这意味着,当第一次调用 lambda 函数时,count 设置为 5item 设置为 3,它们是列表的前两个元素。从 lambda 函数的下一次调用开始,count 递增。因此该解决方案不起作用。

    解决方案是将计数设置为我们选择的值,而不是列表的第一个元素。为此,请使用三个参数调用 reduce。

    def lenReduce(L):
        return reduce(lambda count, item: count + 1, L, 0)
    

    在上面的reduce调用中,count被设置为0,并且item将被设置为每次迭代时从索引0开始的列表元素。

    lenReduce([3,2,1]) 输出3,这是期望的结果。

    【讨论】:

      【解决方案2】:

      reduce 的函数参数有两个参数:上一次调用的返回值和列表中的一个项目。

      def counter(count, item):
          return count + 1
      

      在这种情况下,您并不真正关心item 的值是多少;简单地将其传递给counter 意味着您想要返回计数器的当前值加 1。

      def lenReduce(L):
          return reduce(counter, L)
      

      或者,使用lambda 表达式,

      def lenReduce(L):
          return reduce(lambda count, item: count + 1, L)
      

      即使你的函数忽略了第二个参数,reduce 仍然希望能够将它传递给函数,因此它必须定义为接受两个参数。

      【讨论】:

        猜你喜欢
        • 2021-09-26
        • 2012-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-17
        • 1970-01-01
        • 2021-06-13
        • 2017-06-29
        相关资源
        最近更新 更多