import sys
import random
from collections import Counter
reload(sys)
sys.setdefaultencoding('utf-8')
Count the number of occurrences of an element using a dictionary
generate list
data_list=[random.randint(1,20)for _ in range(10)]
//从1-20随机选择10个数字
Generate statistics dictionary
data_dic=dict.fromkeys(data_list,0)
//选择生成的列表数字作为字典的键,0作为值
Statistics count
for x in data_list:
data_dic[x]+=1
print data_dic
Use Counter to count directly
import library
from collections import Counter
//Counter不仅可以统计列表元素出现次数,还能统计字典元素出现次数,以及字符串中某个字母出现次数。并且还可以按照数量排序
Instructions
c1 = Counter(data_list)
//统计这个列表中元素出现的个数
print c1.most_common(3)
//打印这个列表中出现最多的前三个元素
c2=Counter(data_dict)
//使用方法同上
data_str='aaaabbcc1'
c3=Counter(data_str)
//使用方法同上
Personal blog: www.langzi.fun
welcome to exchange Python development, security testing.