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. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)2. html按鍵開關(guān)如何提交我想需要的值到數(shù)據(jù)庫(kù)3. gvim - 誰有vim里CSS的Indent文件, 能縮進(jìn)@media里面的4. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問題 麻煩幫我看一下5. HTML 5輸入框只能輸入漢字、字母、數(shù)字、標(biāo)點(diǎn)符號(hào)?正則如何寫?6. 跟著課件一模一樣的操作使用tp6,出現(xiàn)了錯(cuò)誤7. PHP類屬性聲明?8. javascript - 請(qǐng)教如何獲取百度貼吧新增的兩個(gè)加密參數(shù)9. html - 微信瀏覽器h5<video>標(biāo)簽問題10. java - 安卓接入微信登錄,onCreate不會(huì)執(zhí)行
