1 Star 0 Fork 0

我是妖怪/python学习笔记初级

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
adv_03.py 607 Bytes
一键复制 编辑 原始数据 按行查看 历史
我是妖怪 提交于 2020-10-27 17:03 +08:00 . 如何统计序列中元素出现的次数
'''
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))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/theonee/python-learning.git
git@gitee.com:theonee/python-learning.git
theonee
python-learning
python学习笔记初级
master

搜索帮助