python - 如何对列表中的列表进行频率统计?
问题描述
例如此列表:
[[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]# 进行频率统计,例如输出结果为:('[’software’,’foundation’]', 3), ('[’of’, ’the’]', 2), ('[’the’, ’python’]', 1)
问题解答
回答1:# coding:utf8from collections import Countera = [[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]print Counter(str(i) for i in a) # 以字典形式返回统计结果print Counter(str(i) for i in a).items() # 以列表形式返回统计结果# -------------- map方法 --------print Counter(map(str, a)) # 以字典形式返回统计结果print Counter(map(str, a)).items() # 以列表形式返回统计结果回答2:
from collections import Counterdata = [[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]cnt = Counter(map(tuple, data))print(list(cnt.items()))回答3:
from itertools import groupbydata = ....print [(k, len(list(g)))for k, g in groupby(sorted(data))]
相关文章:
1. angular.js - react的redux和vue的vuex,angular呢2. javascript - 我写的href跳转地址不是百度,为什么在有的机型上跳转到百度了,有的机型跳转正确3. angular.js - vue/react 渲染内容抖动4. 新手学习vue和node.js的困惑5. python socket 如何接收tcp/ip byte 格式的数据?6. html - 自学php 遇到代码不执行直接在网页上显示 望各位大神不吝赐教7. python - beautifulSoup4 .select(’.bnrName’) 取不到到 text 文字8. 与远程浏览器通信时出错。它可能已经死了。Selenium Web驱动程序9. html - node-module文件有两个在我的项目文件里10. angular.js - webstorm angular 语法没有错误,但有红色波浪线警告?
