python - 如何對列表中的列表進(jìn)行頻率統(tǒng)計?
問題描述
例如此列表:
[[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]# 進(jìn)行頻率統(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 for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題2. win10系統(tǒng) php安裝swoole擴(kuò)展3. extra沒有加載出來4. mysql - php 如何網(wǎng)址中出現(xiàn)該頁標(biāo)題?5. Span標(biāo)簽6. 關(guān)于Mysql數(shù)據(jù)表行轉(zhuǎn)列7. django進(jìn)行數(shù)據(jù)庫的查詢8. PHP求助,求幫忙謝謝各位9. javascript - 釘釘?shù)膃xcel, word文件預(yù)覽是直接用的微軟的office web app,不犯法嗎?10. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?
