python count(计数)相关

Python011

python count(计数)相关,第1张

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)

把用户输入的句子存为字符串,用字符串提供的方法count

例如:

s="abbccc"

s.count("a") ## 1

s.count("c") ## 3