python - 如何對(duì)列表中的列表進(jìn)行頻率統(tǒng)計(jì)?
問(wèn)題描述
例如此列表:
[[’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)
問(wèn)題解答
回答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. mysql儲(chǔ)存json錯(cuò)誤2. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語(yǔ)法實(shí)現(xiàn)存在即更新應(yīng)該使用哪個(gè)標(biāo)簽?3. 哭遼 求大佬解答 控制器的join方法怎么轉(zhuǎn)模型方法4. 怎么php怎么通過(guò)數(shù)組顯示sql查詢(xún)結(jié)果呢,查詢(xún)結(jié)果有多條,如圖。5. sql語(yǔ)句 - 如何在mysql中批量添加用戶(hù)?6. mysql - 表名稱(chēng)前綴到底有啥用?7. mysql - 怎么生成這個(gè)sql表?8. Navicat for mysql 中以json格式儲(chǔ)存的數(shù)據(jù)存在大量反斜杠,如何去除?9. 編輯成功不顯示彈窗10. mysql - 數(shù)據(jù)庫(kù)表中,兩個(gè)表互為外鍵參考如何解決
