(一)问题描述:2-3如何统计序列中元素的出现频度
(二)解决方案
(三) 代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/27 16:07
# @Author : Qiufen.Chen
# @Email : 1760812842@qq.com
# @File : element_frequence.py
# @Software: PyCharm
"""如何统计序列中元素的出现频度"""
from random import randint
data = [randint(0, 20) for _ in range(30)]
print(data) # [6, 19, 17, 14, 18, 2, 12, 13, 16, 3, 5, 2, 12, 6, 3, 4, 4, 13, 0, 8, 0, 15, 20, 18, 8, 3, 17, 10, 11, 10]
dic = dict.fromkeys(data, 0)
print(dic) # {6: 0, 19: 0, 17: 0, 14: 0, 18: 0, 2: 0, 12: 0, 13: 0, 16: 0, 3: 0, 5: 0, 4: 0, 0: 0, 8: 0, 15: 0, 20: 0, 10: 0, 11: 0}
for x in data:
dic[x] += 1
print(dic) # {6: 2, 19: 1, 17: 2, 14: 1, 18: 2, 2: 2, 12: 2, 13: 2, 16: 1, 3: 3, 5: 1, 4: 2, 0: 2, 8: 2, 15: 1, 20: 1, 10: 2, 11: 1}
# ----------------------------------------------------------
from collections import Counter
dic_new = Counter(data)
print(dic_new)
print(dic_new.most_common(3)) # most_common()函数用来实现Top n 功能
# ----------------------------------------------------------
# 文本里的词频统计
import re
txt = open('CodingStyle.txt').read()
list_txt = re.split(' ', txt) # 以空格分割
dic_new_new = Counter(list_txt)
print(dic_new_new.most_common(3))
------------------------------------------------------------------------
注:今天主要学习了 from collections import Counter 模块函数,直接统计每个元素出现的次数
Counter.most_common(n) 用来实现 Top n 功能
------------------------------------------------------------------------
###########################################
(一)问题描述:如何根据字典中值的大小,对字典中的项排序
(二)解决方案
(三)代码
"""如何根据字典中值的大小,对字典中的项排序"""
from random import randint
d = {x: randint(60, 100) for x in 'xyzabc'}
print(d) # {'x': 70, 'y': 77, 'z': 84, 'a': 83, 'b': 63, 'c': 99}
# 利用zip将字典数据转换为元组,在排序
print(sorted(zip(d.values(), d.keys()))) # [(62, 'z'), (68, 'x'), (78, 'y'), (92, 'b'), (94, 'a'), (100, 'c')]
# 传递sorted函数的key参数
print(sorted(d.items(), key=lambda x: x[1])) # [('z', 62), ('x', 68), ('y', 78), ('b', 92), ('a', 94), ('c', 100)]