python - 使用 reduce() 函数的列表长度

python - Length of a list with the reduce() function

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

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

我收到以下错误消息:

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

来自柏林的问候。 ;-)

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

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

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

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

或者,使用 lambda 表达式,

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

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

lenReduce([5,3,1])

returns 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 这是期望的结果。