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 - angularjs的自定义过滤器如何给文字加颜色?2. javascript - 如何让移动端网页的输入框固定在底部?3. MySQL中无法修改字段名的疑问4. docker镜像push报错5. angular.js - angular内容过长展开收起效果6. 请教各位大佬,浏览器点 提交实例为什么没有反应7. python的前景到底有大?如果不考虑数据挖掘,机器学习这块?8. javascript - 微信小程序封装定位问题(封装异步并可能多次请求)9. 大家好,请问在python脚本中怎么用virtualenv激活指定的环境?10. python - flask表单 如何把提交多行数据在服务端读取出来?
