1 # python计数器Counter 2 # 需导入模块collections 3 import collections 4 5 # 统计各个字符出现的次数,以字典形式返回 6 obj = collections.Counter(‘adfsdfsdfswrwerwegfhgfhgh‘) 7 print obj 8 9 # 按参数给定的个数返回 10 print obj.most_common(4)
# 执行结果显示 Counter({‘f‘: 5, ‘d‘: 3, ‘g‘: 3, ‘h‘: 3, ‘s‘: 3, ‘w‘: 3, ‘e‘: 2, ‘r‘: 2, ‘a‘: 1}) [(‘f‘, 5), (‘d‘, 3), (‘g‘, 3), (‘h‘, 3)]
时间: 2024-11-05 02:19:09