【Python教程】统计序列中元素出现频度的详细方法
生活随笔
收集整理的這篇文章主要介紹了
【Python教程】统计序列中元素出现频度的详细方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
例1:從隨機(jī)列表中,找到找到出現(xiàn)次數(shù)最高的3個(gè)元素,及出現(xiàn)次數(shù)
方法一:
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間,隨機(jī)生產(chǎn)一個(gè)長(zhǎng)度100的列表; dict.fromkeys(date, 0)#以列表的值(不重復(fù)使用)做key,以0做值,生產(chǎn)字典; for x in date:c[x] += 1#統(tǒng)計(jì)隨機(jī)list中各元素?cái)?shù)量;c2 = sorted(c.items(), key = lambda k:k[1])#對(duì)統(tǒng)計(jì)的元素?cái)?shù)量進(jìn)行排序,以[(key,value)]形式;c3 = c2[len(c2)-3:]#返回最后3組數(shù)據(jù),為目標(biāo)結(jié)果;方法二:使用collections下的Counter對(duì)象
''' 學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個(gè)Python學(xué)習(xí)交流QQ群:531509025 尋找有志同道合的小伙伴,互幫互助,群里還有不錯(cuò)的視頻學(xué)習(xí)教程和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中元素種類和數(shù)量,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)#返回出現(xiàn)頻率最多的3組數(shù)據(jù);例2:統(tǒng)計(jì)一片英文文章中,出現(xiàn)頻度最高的10個(gè)單詞,及出現(xiàn)次數(shù)
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))#對(duì)txt數(shù)據(jù)進(jìn)行分割后,得到一個(gè)list,并將list內(nèi)元素種類和數(shù)量進(jìn)行統(tǒng)計(jì); c.most_common(10)#將字典c1內(nèi)數(shù)量最多的10個(gè)元素;總結(jié)
以上是生活随笔為你收集整理的【Python教程】统计序列中元素出现频度的详细方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python教程】常见字符串去除空格的
- 下一篇: 【Python教程】两种方法教你拆分含有