第一次迭代就返回 ,所以這個(gè)函數(shù)返回的就是 第一個(gè)元素了。
Python中有 現(xiàn)成的模塊做這個(gè),下面代碼:
import?collections
data?=?[1,2,5,10,-20,5,5]
most_common_elem?=?collections.Counter(data).most_common()
##?下面懶得寫了。。。?從返回結(jié)果中?挑選?元素吧。。。
解釋:可以查看 Counter 的help 信息。
如果自己定義這個(gè)函數(shù)的話:
data?=?[1,2,5,10,-20,5,5]
def?most_common(data):
????if?not?data:
????????return?data
????counter_sort?=?sorted(map(lambda?x:(data.count(x),x),set(data)))
????most_num?=?counter_sort[-1][0]
????return?list(map(lambda?x:x[-1],filter(lambda?x:x[0]?==?most_num,counter_sort)))
????
##?用推導(dǎo)式再試試。。。
def?most_common(data):
????if?not?data:
????????return?data
????counter_sort?=?sorted([(data.count(x),x)?for?x?in?set(data)])
????most_num?=?counter_sort[-1][0]
????return?[x[-1]?for?x?in?counter_sort?if?x[0]?==?most_num]
沒有做 太多的 參數(shù)檢查,下午有點(diǎn)困。就這樣吧。。。