1. 程式人生 > >問題3:如何統計序列中元素的出現頻度

問題3:如何統計序列中元素的出現頻度

items 英文 進行 文章 打開 int 出現 lec count

例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] += 1 c2 = sorted(c.items(), key = lambda k:k[1]) c3 = c2[len(c2)-3:] print(c3)
  1. date = [randint(0, 20) for _ in range(100)]:在0~20間,隨機生產一個長度100的列表;
  2. dict.fromkeys(date, 0):以列表的值(不重復使用)做key,以0做值,生產字典;
  3. for x in date: c[x] += 1:統計隨機list中各元素數量;
  4. c2 = sorted(c.items(), key = lambda k:k[1]):對統計的元素數量進行排序,以[(key,value)]形式;
  5. c3 = c2[len(c2)-3:]:返回最後3組數據,為目標結果;

方法二:使用collections下的Counter對象

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)
  1. 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})
  2. c1.most_common(3),返回出現頻率最多的3組數據;

例2:統計一片英文文章中,出現頻度最高的10個單詞,及出現次數

import re

txt = open(‘文件x‘).read()

c = Counter(re.split(‘\W+‘, txt))

c1 = c.most_common(10) print(c1)
  1. txt = open(‘文件x‘).read():打開文件x;
  2. Counter(re.split(‘\W+‘, txt)):對txt數據進行分割後,得到一個list,並將list內元素種類和數量進行統計;
  3. c.most_common(10):將字典c1內數量最多的10個元素;

問題3:如何統計序列中元素的出現頻度