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 - ElementUI tree控件怎么通过子节点去找到父节点?2. javascript - vue.js插件中的全局方法,全局资源和实例方法区别是什么?3. android - 环信Easeui导入后启动报错UnsatisfiedLinkError4. linux - python ImportError: No module named ’***’5. 文本处理 - 求教使用python库提取pdf的方法?6. python - celery 如何解决worker和client代码同步问题7. flask - Python使用redis发布订阅时,监听频道时出现的问题?【一句话描述不清楚,请各位细看内容】8. python scrapy爬虫错误9. python - flask blog 添加域名10. python-appium代码运行报错

网公网安备