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 - 記得以前在哪里看過一個估算時間的網站2. python - 啟動Eric6時報錯:’qscintilla_zh_CN’ could not be loaded3. css3 - 我想要背景長度變化,而文字不移動,要怎么修改呢4. android下css3動畫非常卡,GPU也不差啊5. python - 有什么好的可以收集貨幣基金的資源?6. MySQL中的enum類型有什么優點?7. javascript - 關于<a>元素與<input>元素的JS事件運行問題8. javascript - vue 怎么渲染自定義組件9. javascript - 同步方式寫異步到底指什么?10. css3 - 純css實現點擊特效
