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. mysql - python开发web service 中数据库链接和释放应该怎么处理?2. javascript - 请问要怎么透过 API 来改变构件的颜色?3. html5 - 新手提问:为什么form表单的post请求 路由处理不了4. 网页爬虫 - 用Python3的requests库模拟登陆Bilibili总是提示验证码错误怎么办?5. 谷歌访问助手安装不了6. javascript - 给js写的盒子添加css样式,css样式没起作用。7. angular.js - angurlarJS的安卓的微信端中用加载ngCookies会出错的问题8. javascript - 移动端 怎么让用户调用自身的地图软件9. javascript - es5中Object.seal()密封对象后,可以修改对象原型上的属性吗?10. 网页爬虫 - Python爬虫入门知识

网公网安备