Counter用来统计集合中元素出现的次数.

Counterdict的子类, 每个键值对都表示元素和元素出现的次数.

创建Counter对象

Counter([iterable-or-mapping])

参数:需要统计的迭代类型或mapping 类型

from collections import Counter

# 通过可迭代类型创建一个 Counter
c1 = Counter("abcabc3344efg")

print(c1)

# 通过 dict 创建一个 Counter
c2 = Counter({"a": 3, "b": 4})    # 表示 a 出现了3次
print(c2)

# 通过关键字创建一个 Counter
c3 = Counter(cats=4, dogs=8)    # 表示 cats 出现了4次
print(c3)


有用的几个方法

elements()

根据统计结果, 返回一个包含所有元素的可迭代类型的对象

most_common(n)

返回出现次数最多的前n个元素

from collections import Counter

c1 = Counter("abcabc3344efg")
print(sorted(c1.elements()))    # 所有的元素
print(c1.most_common(2))

c2 = Counter({"a": 3, "b": 4})
print(sorted(c2.elements()))
print(c2.most_common(2))

c3 = Counter(cats=4, dogs=8)
print(sorted(c3.elements()))
print(c3.most_common(1))

Copyright © 李振超 2018 all right reserved,powered by Gitbook
该文件最后修订时间: 2018-02-25 07:12:09

results matching ""

    No results matching ""