python - 如何對列表中的列表進行頻率統(tǒng)計?
問題描述
例如此列表:
[[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]# 進行頻率統(tǒng)計,例如輸出結(jié)果為:('[’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) # 以字典形式返回統(tǒng)計結(jié)果print Counter(str(i) for i in a).items() # 以列表形式返回統(tǒng)計結(jié)果# -------------- map方法 --------print Counter(map(str, a)) # 以字典形式返回統(tǒng)計結(jié)果print Counter(map(str, a)).items() # 以列表形式返回統(tǒng)計結(jié)果回答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))]
相關(guān)文章:
1. css - div內(nèi)部滾動,安卓沒有滾動條(非body滾動),有什么辦法可以顯示嗎?2. windows-7 - win7下使用cmder,如何設(shè)置vim的tab為4個空格?3. javascript - vue中父組件向子組件傳遞Object時,如何避免TypeError?4. python字符編碼轉(zhuǎn)換5. javascript - js怎么實現(xiàn)jq的addclass,removeclass,例如本來是 class="aa",要變成class="aa bb"6. html5 - mui dialog 如何配置type屬性7. javascript - 微信小程序里怎么把頁面轉(zhuǎn)成圖片分享8. javascript - 為什么用JS設(shè)置a標簽的diplay無效,在CSS中卻有效?9. 隨機產(chǎn)生200個小寫英文字母,并統(tǒng)計個數(shù),這是在網(wǎng)上看到的粒子,我想問怎樣把它變得更簡便?10. Python使用graphviz畫流程圖過程解析
