本文實(shí)例為大家分享了python統(tǒng)計(jì)序列中元素的具體代碼,供大家參考,具體內(nèi)容如下
問(wèn)題1:
隨機(jī)數(shù)列[12,5,8,7,8,9,4,8,5,...] 中出現(xiàn)次數(shù)最高的3個(gè)元素,他們出現(xiàn)的次數(shù)
問(wèn)題2:
對(duì)某英文文章的單詞,進(jìn)行詞頻統(tǒng)計(jì),找出出現(xiàn)次數(shù)最搞得10個(gè)單詞,他們出現(xiàn)的次數(shù)是多少?
上面問(wèn)題都是以字典的形式保存結(jié)果
如何解決問(wèn)題1?
方法1:
#!/usr/bin/python3 from random import randint def count_seq(data): # 初始化統(tǒng)計(jì)結(jié)果字典,data中的key作為結(jié)果字典的key,0作為每個(gè)key的初始值 result_c = dict.fromkeys(data, 0) # 循環(huán)data,對(duì)字典中中碰到的值進(jìn)行 +1 ,循環(huán)完成后就是結(jié)果 for x in data: result_c[x] += 1 return result_c if __name__ == '__main__': # 生成20個(gè)隨機(jī)數(shù) data = [randint(0, 20) for _ in range(20)] print(data) # 結(jié)果 result_c = count_seq(data) for i in result_c: print(i, result_c[i])
方法2:
使用 collections下Counter對(duì)象
#!/usr/bin/python3 from random import randintfrom collections import Counter def count_seq(data): # 創(chuàng)建Counter對(duì)象,并把打他傳遞進(jìn)去 median_c = Counter(data) # 返回統(tǒng)計(jì)最大的3個(gè)數(shù) return median_c.most_common(3) if __name__ == '__main__': # 生成20個(gè)隨機(jī)數(shù) data = [randint(0, 20) for _ in range(20)] print(data) # 結(jié)果 result_c = count_seq(data) print(result_c, dict(result_c))
問(wèn)題2如何解決?
import refrom collections import Counter def count_words(): # 讀取文件 with open('english_article', 'r', encoding='utf-8') as data: print() # 文件單詞分割 data_list = re.split('/W+', data.read()) # 單詞統(tǒng)計(jì) words = Counter(data_list) # 取單詞統(tǒng)計(jì)最大的10個(gè)值 return words.most_common(10) if __name__ == '__main__': result = count_words() print(result)以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林站長(zhǎng)站。
新聞熱點(diǎn)
疑難解答
圖片精選