需求
随着人工智能,机器学习等普及,有Pillow图像识别。但当在平时写代码中遇见对一个列表中的元素重复出现的次数统计时,或者一段英文对话,需要你计算出本段文章内各个单词出现的次数时,当然可以采用以上高级的机器学习分词。但往往是一个简单的需求,却需要兴师动众的搬出大军进行搏杀。接下来我将采用简单的几行代码进行统计。
解决方案
1.首先采用遍历列表,取出元素进行判断是否在列表中,然后再记录改元素为key,次数加1为value的字典中。
2.首次出现直接key:1,重复出现则取出key对应的value进行加1操作即可。
封装成函数实现
In[10]: def count_list(lists): # 定义一个实现函数
...: dicts = {} # 存放统计结果
...: for li in lists:
...: if li in lists:
...: if dicts.get(li): # 再次统计
...: dicts.update({li: dicts.get(li)+1})
...: else: # 首次统计
...: dicts.update({li: 1})
...: return dicts #返回结果
...:
案例:列表统计
In[10]: a = [1,2,3,1,2,3,4,5,4,1,2,3,14,4,5,11,22]
In[11]: count_list(a)
Out[11]: {1: 3, 2: 3, 3: 3, 4: 3, 5: 2, 11: 1, 14: 1, 22: 1}
案例:一段文章统计
In[12]: b = "This is a computer os, it is a very good and very nice kernel. I like it and will speed much time to study it ." # 定义一段话
In[13]: b
Out[13]: 'This is a computer os, it is a very good and very nice kernel. I like it and will speed much time to study it .'
In[14]: c = b.split() #拆解处理,形成列表
In[15]: c
Out[15]:
['This',
'is',
'a',
'computer',
'os,',
'it',
'is',
'a',
'very',
'good',
'and',
'very',
'nice',
'kernel.',
'I',
'like',
'it',
'and',
'will',
'speed',
'much',
'time',
'to',
'study',
'it',
'.']
In[16]: count_list(c) # 统计的结果
Out[16]:
{'.': 1,
'I': 1,
'This': 1,
'a': 2,
'and': 2,
'computer': 1,
'good': 1,
'is': 2,
'it': 3,
'kernel.': 1,
'like': 1,
'much': 1,
'nice': 1,
'os,': 1,
'speed': 1,
'study': 1,
'time': 1,
'to': 1,
'very': 2,
'will': 1}