python 中统计列表中每个元素的频数

 

001、

>>> test = [10, 20, 10, 30, 30, 10, 40, 10, 30]  ## 测试列表
>>> from collections import Counter as ct       ## 借助Counter函数实现
>>> ct(test)
Counter({10: 4, 30: 3, 20: 1, 40: 1})
>>> dict(ct(test))                              ## 转换为字典
{10: 4, 20: 1, 30: 3, 40: 1}

 

002、

>>> test
[10, 20, 10, 30, 30, 10, 40, 10, 30]
>>> result = dict()
>>> for i in test:                    ## 利用循环结构实现
...     result[i] = test.count(i)
...
>>> result
{10: 4, 20: 1, 30: 3, 40: 1}

 

参考:https://blog.csdn.net/m0_57099761/article/details/123464340

posted @   小鲨鱼2018  阅读(142)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2021-08-12 c primer plus 5编程练习
点击右上角即可分享
微信分享提示