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. sublime text3安裝package control失敗2. wordpress里,這樣的目錄列表是屬于小工具還是啥?3. python如何設置一個隨著系統時間變化的動態變量?4. 常量在外面不加引號會報錯。5. mysql federated引擎無法開啟6. 一直報這個錯誤7. mysql - 大部分數據沒有行溢出的text字段是否需要拆表8. 我的怎么不顯示啊,話說有沒有QQ群什么的9. mysql 為什么主鍵 id 和 pid 都市索引, id > 10 走索引 time > 10 不走索引?10. MySQL 使用 group by 之后然后 IFNULL(COUNT(*),0) 為什么還是會獲得 null
