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. node.js - mongodb查找子對象的名稱為某個值的對象的方法2. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????3. 運行python程序時出現“應用程序發生異常”的內存錯誤?4. html5 - datatables 加載不出來數據。5. 前端 - @media query 使用出現的問題?6. 利用IPMI遠程安裝centos報錯!7. javascript - 在 model里定義的 引用表模型時,model為undefined。8. 測試自動化html元素選擇器元素ID或DataAttribute [關閉]9. javascript - QQ第三方登錄的問題10. html5和Flash對抗是什么情況?

網公網安備