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. java - ajax成功到后台不知道为什么一直回调失败函数2. 在介绍Node.js的相关资料中,$ npm install express中的$代表什么?3. javascript - app中集成轻量级富文本编辑器?4. node.js - node exec 执行没反应5. 后代选择器与元素选择器6. javascript - hexo可以配置文章文件名为随机数么?7. Java IO流-InputStream是抽象类,也能调方法?(如图)8. html5 - vue-cli 装好了 新建项目的好了,找不到项目是怎么回事?9. html5 - Android混合开发10. python3.x - python 中的maketrans在utf-8文件中该怎么使用

网公网安备