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. Docker for Mac 创建的dnsmasq容器连不上/不工作的问题2. docker - 如何修改运行中容器的配置3. boot2docker无法启动4. 为什么我ping不通我的docker容器呢???5. docker镜像push报错6. golang - 用IDE看docker源码时的小问题7. angular.js - angular内容过长展开收起效果8. docker绑定了nginx端口 外部访问不到9. javascript - 移动端 点击弹出遮罩层 加断点调试就行 不加断点就不行10. css3 - IE浏览器下,一个元素设置overflow:auto后,出现下拉滚动条,拖动滚动条图片会移动,但文字不移动

网公网安备