欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何統(tǒng)計序列中元素

 更新時間:2020年07月31日 11:15:42   作者:北門吹雪  
這篇文章主要為大家詳細介紹了python如何統(tǒng)計序列中的元素,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了python統(tǒng)計序列中元素的具體代碼,供大家參考,具體內(nèi)容如下

問題1:

       隨機數(shù)列[12,5,8,7,8,9,4,8,5,...] 中出現(xiàn)次數(shù)最高的3個元素,他們出現(xiàn)的次數(shù)

問題2:

       對某英文文章的單詞,進行詞頻統(tǒng)計,找出出現(xiàn)次數(shù)最搞得10個單詞,他們出現(xiàn)的次數(shù)是多少?

上面問題都是以字典的形式保存結果

如何解決問題1?

方法1:

#!/usr/bin/python3
 
from random import randint
 
 
def count_seq(data):
  
 # 初始化統(tǒng)計結果字典,data中的key作為結果字典的key,0作為每個key的初始值
 result_c = dict.fromkeys(data, 0)
  
 # 循環(huán)data,對字典中中碰到的值進行 +1 ,循環(huán)完成后就是結果
 for x in data:
  result_c[x] += 1
 return result_c
 
if __name__ == '__main__':
 # 生成20個隨機數(shù)
 data = [randint(0, 20) for _ in range(20)]
 print(data)
  
 # 結果
 result_c = count_seq(data)
 for i in result_c:
  print(i, result_c[i])

方法2:

使用 collections下Counter對象

#!/usr/bin/python3
 
from random import randint
from collections import Counter
 
 
def count_seq(data):
  
 # 創(chuàng)建Counter對象,并把打他傳遞進去
 median_c = Counter(data)
  
 # 返回統(tǒng)計最大的3個數(shù)
 return median_c.most_common(3)
 
if __name__ == '__main__':
 # 生成20個隨機數(shù)
 data = [randint(0, 20) for _ in range(20)]
 print(data)
  
 # 結果
 result_c = count_seq(data)
 print(result_c, dict(result_c))

問題2如何解決?

import re
from 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)計
 words = Counter(data_list)
 # 取單詞統(tǒng)計最大的10個值
 return words.most_common(10)
 
if __name__ == '__main__':
 result = count_words()
 print(result)

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論