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