文章目录[隐藏]
一、使用字典 dict 统计
循环遍历出一个可迭代对象的元素,如果字典中没有该元素,那么就让该元素作为字典的键,并将该键赋值为1,如果存在则将该元素对应的值加1。
lists = ['a','a','b',1,2,3,1] count_dist = dict() for i in lists: if i in count_dist: count_dist[i] += 1 else: <div style="color:transparent">本文来源gaodai.ma#com搞##代!^码@网*</div> count_dist[i] = 1 print(count_dist) # {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1}
二、使用 collections.defaultdict 统计
defaultdict(parameter)
接受一个类型参数,例如:int、float、str 等。
传递进来的类型参数,不是用来约束值的类型,更不是约束键的类型,而是当键不存在时,实现一种值的初始化。
defaultdict(int) -- 初始化为0 defaultdict(float) -- 初始化为0.0 defaultdict(str) -- 初始化为'' from collections import defaultdict lists = ['a','a','b',1,2,3,1] count_dict = defaultdict(int) for i in lists: count_dict[i] += 1 print(count_dict) # defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})
三、List count方法
count()
方法用于统计某个元素在列表中出现的次数。
使用语法:
# 使用语法 list.count(obj) # 返回次数
统计单个对象次数:
# 统计单个对象次数 aList = [123, 'abc', 'good', 'abc', 123] print("Count for 123 :", aList.count(123)) print("Count for abc :", aList.count('abc')) # Count for 123 : 2 # Count for abc : 2
统计List中每一个对象次数:
test = ["aaa","bbb","aaa","aaa","ccc","ccc","ddd","aaa","ddd","eee","ddd"] print(test.count("aaa")) # 4 print(test.count("bbb")) # 1 test_result = [] for i in test: if i not in test_result: test_result.append(i) print(test_result) for i in test_result: print(f"{i}:{test.count(i)}") ''' 4 1 ['aaa', 'bbb', 'ccc', 'ddd', 'eee'] aaa:4 bbb:1 ccc:2 ddd:3 eee:1 '''
四、使用集合(set)和列表(list)统计
先用 set
去重,然后循环把每一个元素和对应的次数 list.count(item)
组成元组。
''' 学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' lists = ['a','a','b',1,2,3,1] count_set = set(lists) print(count_set) # 集合去重 # {1, 2, 3, 'b', 'a'} count_list = list() for i in count_set: count_list.append((i, lists.count(i))) print(count_list) # [(1, 2), (2, 1), (3, 1), ('b', 1), ('a', 2)]
五、collections.Counter方法
Counter
是一个容器对象,使用 collections
模块中的 Counter
类可以实现 hash
对象的统计。
Counter
是一个无序的容器类型,以字典的键值对形式存储,其中元素作为 key,其计数作为 value。
计数值可以是任意的 Interger
(包括0和负数)。
Counter() 对象还有几个可调用的方法:
most_common(n)
— TOP n 个出现频率最高的元素elements
— 获取所有的键 通过list转化update
— 增加对象subtrct
— 删除对象- 下标访问 a[‘xx’] –不存在时返回0
import collections c = collections.Counter('helloworld')