Python论坛  - 讨论区

标题:Python Cookbook 之 Counter容器的使用范例

2014年03月14日 星期五 09:26

Python中的Counter主要用于统计某个key出现的次数。官方文档中这样说:

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

示例代码:

import random
numbers=[]

for i in range(20):
    d=random.randint(1,5)
    numbers.append(d)
    
print(numbers)

from collections import Counter
counts=Counter(numbers)
top3=counts.most_common(3)
print(top3)

print(counts)

参考资料:

http://docs.python.org/3/library/collections.html#collections.Counter

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号