【Python教程】统计序列中元素出现频度的详细方法
生活随笔
收集整理的這篇文章主要介紹了
【Python教程】统计序列中元素出现频度的详细方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
例1:從隨機列表中,找到找到出現次數最高的3個元素,及出現次數
方法一:
from random import randint date = [randint(0, 20) for _ in range(100)] c = dict.fromkeys(date, 0) for x in date:c[x] += 1c2 = sorted(c.items(), key = lambda k:k[1])c3 = c2[len(c2)-3:] print(c3) --------------------------------------------------------------------------------- date = [randint(0, 20) for _ in range(100)]#在0~20間,隨機生產一個長度100的列表; dict.fromkeys(date, 0)#以列表的值(不重復使用)做key,以0做值,生產字典; for x in date:c[x] += 1#統計隨機list中各元素數量;c2 = sorted(c.items(), key = lambda k:k[1])#對統計的元素數量進行排序,以[(key,value)]形式;c3 = c2[len(c2)-3:]#返回最后3組數據,為目標結果;方法二:使用collections下的Counter對象
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' from collections import Counter from random import randint date = [randint(0, 20) for _ in range(100)] c1 = Counter(date) c2 = c1.most_common(3) print(c2) ---------------------------------------------------------------------- Counter(date)#直接得到date中元素種類和數量,Counter({0: 7, 14: 7, 15: 7, 17: 7, 13: 6, 11: 6, 12: 5, 6: 5, 8: 5, 9: 5, 20: 4, 16: 4, 1: 4, 19: 4, 7: 4, 3: 4, 2: 4, 18: 3, 5: 3, 4: 3, 10: 3}) c1.most_common(3)#返回出現頻率最多的3組數據;例2:統計一片英文文章中,出現頻度最高的10個單詞,及出現次數
import retxt = open('文件x').read()c = Counter(re.split('\W+', txt)) c1 = c.most_common(10) print(c1) ------------------------------------------------------------------------ txt = open('文件x').read()#打開文件x; Counter(re.split('\W+', txt))#對txt數據進行分割后,得到一個list,并將list內元素種類和數量進行統計; c.most_common(10)#將字典c1內數量最多的10個元素;總結
以上是生活随笔為你收集整理的【Python教程】统计序列中元素出现频度的详细方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python教程】常见字符串去除空格的
- 下一篇: 【Python教程】两种方法教你拆分含有