【Python】統計序列中元素出現次數

import sys
import random
from collections import Counter
reload(sys)
sys.setdefaultencoding('utf-8')

使用字典方式統計元素出現次數

生成列表

data_list=[random.randint(1,20)for _ in range(10)]
//從1-20隨機選擇10個數字

生成統計字典

data_dic=dict.fromkeys(data_list,0)
//選擇生成的列表數字作爲字典的鍵,0作爲值

統計次數計算

for x in data_list:
    data_dic[x]+=1
print data_dic

使用Counter直接統計

導入庫

from collections import Counter
//Counter不僅可以統計列表元素出現次數,還能統計字典元素出現次數,以及字符串中某個字母出現次數。並且還可以按照數量排序

使用方法

c1 = Counter(data_list)
//統計這個列表中元素出現的個數
print c1.most_common(3)
//打印這個列表中出現最多的前三個元素

c2=Counter(data_dict)
//使用方法同上

data_str='aaaabbcc1'
c3=Counter(data_str)
//使用方法同上

個人博客:www.langzi.fun
歡迎交流Python開發,安全測試。

發佈了69 篇原創文章 · 獲贊 100 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章