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. php - 两个表数据怎么插到一个模板中,并按时间排序?2. python - 如何解决程序运行太久之后被操作系统暂停的情况?3. javascript - axios请求回来的数据组件无法进行绑定渲染4. CSS3的渐变属性的疑惑5. vue.js - weex 没有背景图片属性怎么办?6. css - transform-origin 旋转参考点7. MYSQL 运算的问题8. javascript - 单个页面执行多个jsonp的ajax请求,如何判断一个ajax请求执行完毕执行再另一个?9. 微信端电子书翻页效果10. 使用git管理webpack的代码时多人怎么协作?一般托管哪些文件?

网公网安备