带有目标值的Python计数器



我试图采取,作为参数,两个值:列表和目标值。它返回目标值在列表中出现的次数。

def countTarget(myList, target):
    #initialize the counter to  zero
    counter =   0
    for element in  myList:
        #compare    the value   in  the list to the target  value
        #if they    are the same,   increment   the counter
        if  element ==  target:
            counter =   counter +   1
    return  counter

好吧,会有更好的答案,但这是一个。

def countTarget(myList, target):
    return sum([x == target for x in myList])

编辑

在评论中有一个更好的选择。

myList.count(target)

使用Counter类。这是一种特殊类型的字典,它可以很好地计算列表中特定值的频率(而不是自己使用字典),因为它可以避免一些错误,比如在试图计算列表中不存在的目标时遇到KeyError(另一方面,Counter只返回0)。

from collections import Counter
def countTarget(myList, target):
  return Counter(myList)[target]

或者,您可以使用内置的count函数列表,正如在您的问题下面的评论中提到的。

def countTarget(myList, target): return myList.count(target)

然而,在这一点上,您的countTarget函数对您没有多大好处。如果你真的想让两个对象都成为参数,你也可以在静态上下文中使用count函数…

list.count(myList, target)

不过说真的,还是用myList.count(target)吧。对于您的用例来说,这可能是最简单和直接的(从外观上看)。如果您需要多次计数目标,那么请考虑保留自己的Counter,如前所述。

最新更新