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. pdo_mysql 值自增写法2. Python, for-else, while-else是否造成了语义歧义 ( 增加心智负担 )?3. MYSQL 运算的问题4. javascript - js 对中文进行MD5加密和python结果不一样。5. javascript - 微信公号里采用七牛上传视频部分手机不能选择文件6. mysql sql where id in(25,12,87) 结果集如何用按照 25 12 87排序?7. mysql多表查询8. PHP中的$this代表当前的类还是方法?9. python3.x - python多进程,不能在同一窗口吗10. 关于python爬虫的问题

网公网安备