时间:2020-10-30 16:22:41 | 栏目:Python代码 | 点击:次
给定一个可迭代sequence,对其中的值进行出现次数统计:
方法1:
def get_counts(sequence): counts = {} for x in sequence: if x in counts: counts[x] += 1 else: counts[x] = 1 return counts
方法2:
利用python中内置的collections
from collections import defaultdict def get_counts2(sequence): counts = defaultdict(int) #所有的值均会被初始化为0 for x in sequence: counts[x] +=1 return counts
方法3:
from collections import Counter counts = Counter(sequence) #其中可以用counts.most_common(10)对出现最多的十个倒序排列
然后对得到的统计排序:
def top_count(count_dic, n=10): #默认取最大的n=10个值 value_key_pairs = [(count,data) for counts,data in cout_dict.items()] value_key_pairs.sort() #sorted(value_key_pairs) 两者均可 return value_key_pairs[-n:]