python - 如何對列表中的列表進行頻率統(tǒng)計?
問題描述
例如此列表:
[[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]# 進行頻率統(tǒng)計,例如輸出結果為:('[’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)計結果print Counter(str(i) for i in a).items() # 以列表形式返回統(tǒng)計結果# -------------- map方法 --------print Counter(map(str, a)) # 以字典形式返回統(tǒng)計結果print Counter(map(str, a)).items() # 以列表形式返回統(tǒng)計結果回答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))]
相關文章:
1. 致命錯誤: Class ’appfacadeTest’ not found2. python - 數(shù)據(jù)無法插入到mysql表里3. docker-compose中volumes的問題4. javascript - 求正則表達式的寫法5. dockerfile - 為什么docker容器啟動不了?6. java - Oracle如何獲取去重結果集中某一條數(shù)據(jù)的下一條數(shù)據(jù)7. css - 關于偽類背景問題8. 老師,請問我打開browsersync出現(xiàn)這個問題怎么解決啊?9. npm install -g browser-sync這個之后出錯 還有人嗎 我都感覺沒人回答問題了10. mysql scripts提示 /usr/bin/perl: bad interpreter
