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 © 2024
京ICP备05028076号