找到列表的模式

时间:2015-07-12 06:26:27

标签: python-3.x

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)  

我似乎无法正确地遍历我的列表...... 我可以使用第二个for循环成功获得第一个返回>>>(模式= 87)的模式但是,我无法搜索列表的其余部分以便它也会返回&gt ;>>(模式= 92)

我已经删除了我在Mode = 92的尝试,你能帮忙填补空白吗?

由于

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分:-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))