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. python中return 语句与 分支语句连用问题2. thinkphp3 count()方法必须加上字段?3. node.js - webpack-dev-server正常运行,webpack打包却出错,怎么办?4. 这是什么情况???5. javascript - 项目的公共文件如图片JS等文件放在 云上,webroot只放jsp文件,怎么将静态文件通过配置文件引入,sp求大神指导6. android - 哪位大神知道java后台的api接口的对象传到前端后输入日期报错,是什么情况?求大神指点7. 怎么php怎么通过数组显示sql查询结果呢,查询结果有多条,如图。我要forsearch里面echo8. 默认输出类型为json,如何输出html9. nginx 504 Gateway Time-out 请问如何设置10. update方法不能更新字段值为0的数据
