python - 如何對列表中的列表進行頻率統計?
問題描述
例如此列表:
[[’software’, ’foundation’], [’of’, ’the’], [’the’, ’python’], [’software’, ’foundation’],[’of’, ’the’], [’software’, ’foundation’]]# 進行頻率統計,例如輸出結果為:('[’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) # 以字典形式返回統計結果print Counter(str(i) for i in a).items() # 以列表形式返回統計結果# -------------- map方法 --------print Counter(map(str, a)) # 以字典形式返回統計結果print Counter(map(str, a)).items() # 以列表形式返回統計結果回答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. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. docker安裝后出現Cannot connect to the Docker daemon.3. css - 定位為absolute的父元素中的子元素 如何設置在父元素的下面?4. java - 請問在main方法中寫成對象名.屬性()并賦值,與直接參參數賦值輸錯誤是什么原因?5. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統有創建日志文件,不寫入日志信息。6. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat7. java - socket類服務端如何防止被ddos攻擊?8. javascript - 圖片鏈接請求一直是pending狀態,導致頁面崩潰,怎么解決?9. python - beautifulsoup獲取網頁內容的問題10. 怎么用css截取字符?
