代码拉取完成,页面将自动刷新
'''
python 高级笔记 如何统计序列中元素出现的次数
来源:https://www.bilibili.com/video/BV1b5411s76z?p=4
'''
from random import randint
import timeit
list01 = [randint(1, 5) for _ in range(20)]
# 基础方案
# 初始字典,序列元素是key
dict01 = dict.fromkeys(list01, 0)
# 遍历序列 累加数量
for i in list01:
dict01[i] += 1
print(dict01)
# 推导式方案
set01 = set(list01)
res = {k: list01.count(k) for k in set01}
print(res)
# Collections.counter 方案
from collections import Counter
print(Counter(list01))
# 前n个
print(Counter(list01).most_common(3))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。