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. javascript - vue-router怎么不能實現跳轉呢2. npm鏡像站全新上線3. 老哥們求助啊4. css3 - 請問一下在移動端CSS布局布局中通常需要用到哪些元素,屬性?5. mySql排序,序號6. html5 - angularjs中外部模版加載無法使用7. django - 后臺返回的json數據經過Base64加密,獲取時用python如何解密~!8. node.js - node 客戶端socket一直報錯Error: read ECONNRESET,用php的socket沒問題哈。。9. tp6表單令牌10. 我的html頁面一提交,網頁便顯示出了我的php代碼,求問是什么原因?
