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. javascript - 关于Js中 this的一道题2. javascript - vue生成一维码?求助!!!!!急3. 求大神帮我看看是哪里写错了 感谢细心解答4. css - 手机页面在安卓和苹果浏览器显示不同的小小问题5. javascript - 修改表单多选项时和后台同事配合的问题。6. javascript - jqery ajax问题7. thinkjs - 使用mysql搭建cms应该如何设计表?或怎样开始?8. javascript - H5页面怎么查看console信息?9. java中没有抽象方法的抽象类有什么意义?仅仅是为了让别人不能创建该类的对象?10. mysql 获取时间函数unix_timestamp 问题?
