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. docker 17.03 怎么配置 registry mirror ?2. javascript - sublime快鍵鍵問題3. javascript - immutable配合react提升性能?4. 實現(xiàn)bing搜索工具urlAPI提交5. javascript - vue-router 地址改變數(shù)據(jù)未改變6. javascript - html5多個label中其中一個觸發(fā)change,如何判斷是哪一個出發(fā)了change7. css - 移動端字體設置問題8. phpstudy8.1支持win11系統(tǒng)嗎?9. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~10. 配置Apache時,添加對PHP的支持時語法錯誤

網(wǎng)公網(wǎng)安備