本文實(shí)例講述了python求眾數(shù)問題的方法,是一個(gè)比較典型的應(yīng)用。分享給大家供大家參考。具體如下:
問題描述:
多重集中重?cái)?shù)最大的元素稱為眾數(shù)...就是一個(gè)可以有重復(fù)元素的集合,在這個(gè)集合中重復(fù)的次數(shù)最多的那個(gè)數(shù)就叫它的眾數(shù)...
如S = [1,2,2,2,3,5] 重?cái)?shù)是2,其重?cái)?shù)為3
實(shí)例代碼如下:
list_num = [] list_num_count = 0 dict_num ={} #從文件讀入,文件第一行為集合中元素的個(gè)數(shù),以后每一行為一個(gè)元素 list_num_count = int(open('input.txt','r').readline()) for line_num, line in enumerate(open("input.txt",'r')): if line_num > 0: list_num += line.split() #將讀到的元素加入的字典中 for item in list_num: if dict_num.has_key(item): dict_num[item] += 1 else: dict_num.setdefault(item,1) pass #找到出現(xiàn)次數(shù)最多的那個(gè)數(shù),找到重?cái)?shù) dict_sort_by_top = {} top_value = 0 for valus in dict_num.itervalues(): if valus> top_value: top_value = valus pass #根據(jù)重?cái)?shù)找到眾數(shù)...這是因?yàn)榭紤]到可能有多個(gè)元素有相同多的重?cái)?shù) the_pop_num = 0 the_pop_num_count = 0 for keys,values in dict_num.iteritems(): if values == top_value: print 'the pop num is %s,and the appear num is %s' % (keys,values) the_pop_num = keys the_pop_num_count = values #輸出到文件,第一行為從數(shù),第二行為重?cái)?shù) write_line = '%s\n%s' %(the_pop_num, the_pop_num_count) open("output.txt",'w').write(write_line)
這里假設(shè)有同級(jí)目錄文件input.txt內(nèi)容如下:
8 11 37 2 37 2 45 99 37
第一行的8代表元素個(gè)數(shù),其后每一行有一個(gè)元素。
測(cè)試環(huán)境為Python2.7.6,
Python程序針對(duì)input.txt文件操作的運(yùn)行結(jié)果如下:
the pop num is 37,and the appear num is 3
同時(shí)生成output.txt文件記錄了眾數(shù)37及其重復(fù)次數(shù)3。
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
