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. python - Scrapy如何得到原始的start_url2. javascript - 從mysql獲取json數(shù)據(jù),前端怎么處理轉(zhuǎn)換解析json類型3. thinkPHP5中獲取數(shù)據(jù)庫數(shù)據(jù)后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙4. linux運維 - python遠程控制windows如何實現(xiàn)5. android - 安卓做前端,PHP做后臺服務(wù)器 有什么需要注意的?6. python - 數(shù)據(jù)與循環(huán)次數(shù)對應(yīng)不上7. django - Python error: [Errno 99] Cannot assign requested address8. python小白 關(guān)于類里面的方法獲取變量失敗的問題9. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?10. 求救一下,用新版的phpstudy,數(shù)據(jù)庫過段時間會消失是什么情況?
