将另一个函数作为开始参数提供给sum()

2024-06-07 13:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在关于打包的教程中看到了下面的函数

我的疑问在于sum(),它将Counter()作为start参数。在这种情况下会发生什么

# Import needed functionality
from collections import Counter

def sum_counters(counters):
  # Sum the inputted counters
  return sum(counters, Counter())

我尝试使用下面的代码进行复制

a=[2,3,3,4,5,5,6]
sum(a,len())

结果:

TypeError: len() takes exactly one argument (0 given)

我无法用Counter()复制它(由于下载collections包时pip中出现错误),也找不到任何提到将函数作为开始参数的文档

有人能解释一下吗。谢谢


Tags: 函数fromimport参数lencounter情况教程
2条回答

My doubt is in the sum() which takes Counter() as the start parameter. What would happen in this case ?

就像在任何其他情况下一样,它采用初始Counter()并将counters的第一个元素添加到它,然后将下一个元素添加到该结果中,依此类推。这与在所有Counter实例之间显式使用+符号相同。要了解那个做了什么,see the documentation

TypeError: len() takes exactly one argument (0 given)

嗯,是的,就像上面说的len需要知道如何获得的长度。我不明白你想要这个sum呼叫do做什么

nor am i able to find any documentation that mentions about giving functions as the start parameters.

collections.Counter不是一个函数;这是一个。然而,len(x)也不是一个函数;这是调用该函数的结果。(类似地,调用collections.Counter类的结果是一个collections.Counter实例),不管start参数来自哪里;重要的是它的。例如:

a=[2,3,3,4,5,5,6]
sum(a,len(a))

a中有7项,因此len(a)等于7,结果与直接写入sum(a, 7)相同。也就是说7 + 2 + 3 + 3 + 4 + 5 + 5 + 6=35

Counter()提供了一个空的Counter实例len不能在没有参数的情况下调用

sum(counters, Counter())大致相当于

result = Counter()
for x in counters:
    result = result + x

您可以这样做,因为加法是为Counter的实例定义的

对于您正在尝试的示例,您希望以空列表的长度作为起始值:

sum(a, len([]))

因为len([]) == 0,它与sum(a, 0)相同,或者只是sum(a)

相关问题 更多 >

    热门问题