python - 如何對(duì)列表中的列表進(jìn)行頻率統(tǒng)計(jì)?
問題描述
例如此列表:
[[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]# 進(jìn)行頻率統(tǒng)計(jì),例如輸出結(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)計(jì)結(jié)果print Counter(str(i) for i in a).items() # 以列表形式返回統(tǒng)計(jì)結(jié)果# -------------- map方法 --------print Counter(map(str, a)) # 以字典形式返回統(tǒng)計(jì)結(jié)果print Counter(map(str, a)).items() # 以列表形式返回統(tǒng)計(jì)結(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. python bottle跑起來以后,定時(shí)執(zhí)行的任務(wù)為什么每次都重復(fù)(多)執(zhí)行一次?2. javascript - vue2.0中,$refs對(duì)象為什么用駝峰的方式獲取不到屬性?3. javascript - vue2如何獲取v-model變量名4. javascript - 求幫助 , ATOM不顯示界面!!!!5. html5 - HTML代碼中的文字亂碼是怎么回事?6. python - 爬蟲模擬登錄后,爬取csdn后臺(tái)文章列表遇到的問題7. javascript - ios返回不執(zhí)行js怎么解決?8. javascript - 能否讓vue-cli的express修改express重啟服務(wù)9. javascript - angular使從elastichearch中取出的文本高亮顯示,如圖所示10. mysql - 分庫(kù)分表、分區(qū)、讀寫分離 這些都是用在什么場(chǎng)景下 ,會(huì)帶來哪些效率或者其他方面的好處
