python count(计数)相关

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python count(计数)相关相关的知识,希望对你有一定的参考价值。

参考技术A 1.定义函数

def get_counts(sequence):

    counts=

    for x in sequence:

        if x  in counts:

            counts[x]+= 1

         else:

              counts[x]=1

    return counts

2.定义函数(利用python标准包)

from collections import defaultdict

def get_counts2(sequence):

    counts=defaultdict(int)#所以得值均会被初始化W为0

    for x in sequence:

        if x  in counts:

            counts[x]+= 1

    return counts

3.python标准库中找到collections.Counter类

from collections improt Counter

counter(sequence)

以上是关于python count(计数)相关的主要内容,如果未能解决你的问题,请参考以下文章