2015-07-12 25 views
-2
L = [98,75,92,87,89,90,92,87] 

def mode(L): 

    shows = [] 
    modeList = [] 

    L.sort() 

    length = len(L) 

    for num in L: 
     count = L.count(num) 
     shows.append(count) 

    print 'List = ', L 

    maxI = shows.index(max(shows)) 

    for i in shows: 
     if i == maxI: 
      if modeList == []: 
       mode = L[i] 
       modeList.append(mode) 
       print 'Mode = ', mode 
      elif mode not in modeList: 
       mode = L[i] 
       modeList.append(mode) 
       print 'Mode = ', mode 
      return mode 


mode(L) 

我似乎無法通過我的列表迭代正常...... 我能順利拿到第一模式返回>>>(模式= 87)使用第二for循環然而,我不能讓它搜索列表的其餘部分,以便它也將返回>>>(Mode = 92)查找表的模式

我已經刪除了我在Mode = 92的嘗試,你能幫忙填寫空白?

感謝

+1

你爲什麼問同一個問題[再次](http://stackoverflow.com/questions/31364464/python-3-find -THE模式對的一列表)? – Sait

回答

-2

上的代碼幹得好。我重寫了一下。請參見下面的代碼:

L = [98,75,92,87,89,90,92,87] 

def mode(L): 

    # Create a frequency table 
    freq = {} 
    for num in L: 
     if not num in freq: 
      freq[num] = 1 
     else: 
      freq[num] += 1 

    # Gets maximal occurence 
    maxoccurence = 0 
    for f in freq: 
     maxoccurence = max(maxoccurence, freq[f]) 

    # Put all the numbers with the occurence in a list 
    modes = [] 
    for f in freq: 
     if freq[f] == maxoccurence: 
      modes += [f] 

    # Returns the list 
    return modes 

print(mode(L)) 
0

同樣的想法與collections.Counter

from collections import Counter 

L = [98,75,92,87,89,90,92,87] 

def mode(L): 
    # count the occurring frequencies 
    count = Counter(L) 

    # find the max 
    mx = max(count.values()) 

    # collect the frequencies that occur the most 
    modes = [f for f, m in count.items() if m == mx] 

    return modes 

print(mode(L)) 
# [87, 92]