寻找列表的众数

154

给定一个项目列表,回想一下,列表的众数是出现最频繁的项目。

我想知道如何创建一个函数,可以找到列表的众数,但如果列表没有众数(例如,列表中的所有项目仅出现一次),则显示消息。我想自己从头开始制作这个函数,而不引入任何函数。


抱歉,您能解释一下“列表模式”具体是什么意思吗? - Vikas
8
“众数”是一组数据中出现次数最多的元素(如果有的话)。有些定义将其扩展为计算所有这样的元素的算术平均值,如果有多个众数的话。 - Jeremy Roman
1
这里有很多错误的答案! 例如assert(mode[1, 1, 1]) == Noneassert(mode[1, 2, 3, 4]) == None。一个数字要成为“众数”,它必须在列表中出现的次数比至少另一个数字多,并且它不能是列表中唯一的数字。 - lifebalance
27个回答

0
def mode(data):
    lst =[]
    hgh=0
    for i in range(len(data)):
        lst.append(data.count(data[i]))
    m= max(lst)
    ml = [x for x in data if data.count(x)==m ] #to find most frequent values
    mode = []
    for x in ml: #to remove duplicates of mode
        if x not in mode:
        mode.append(x)
    return mode
print mode([1,2,2,2,2,7,7,5,5,5,5])

0
#function to find mode
def mode(data):  
    modecnt=0
#for count of number appearing
    for i in range(len(data)):
        icount=data.count(data[i])
#for storing count of each number in list will be stored
        if icount>modecnt:
#the loop activates if current count if greater than the previous count 
            mode=data[i]
#here the mode of number is stored 
            modecnt=icount
#count of the appearance of number is stored
    return mode
print mode(data1)

你应该在代码中添加注释或更多细节来解释你的答案。 - Michael

0
这里有一个简单的函数,用于获取列表中出现的第一个众数。它创建了一个字典,以列表元素作为键和出现次数,并读取字典值以获取众数。
def findMode(readList):
    numCount={}
    highestNum=0
    for i in readList:
        if i in numCount.keys(): numCount[i] += 1
        else: numCount[i] = 1
    for i in numCount.keys():
        if numCount[i] > highestNum:
            highestNum=numCount[i]
            mode=i
    if highestNum != 1: print(mode)
    elif highestNum == 1: print("All elements of list appear once.")

0
如果您想要一种清晰的方法,适用于课堂教学,并且仅使用列表和字典理解,您可以这样做:
def mode(my_list):
    # Form a new list with the unique elements
    unique_list = sorted(list(set(my_list)))
    # Create a comprehensive dictionary with the uniques and their count
    appearance = {a:my_list.count(a) for a in unique_list} 
    # Calculate max number of appearances
    max_app = max(appearance.values())
    # Return the elements of the dictionary that appear that # of times
    return {k: v for k, v in appearance.items() if v == max_app}

0

或许可以尝试以下方法。它的时间复杂度为O(n),返回一个浮点数(或整数)列表。它经过了全面自动化测试。它使用了collections.defaultdict,但我认为您不会反对使用它。您也可以在https://stromberg.dnsalias.org/~strombrg/stddev.html找到它。

def compute_mode(list_: typing.List[float]) -> typing.List[float]:
    """                       
    Compute the mode of list_.

    Note that the return value is a list, because sometimes there is a tie for "most common value".
                                                                        
    See https://dev59.com/jWgv5IYBdhLWcg3wKtvj
    """                                                                                                        
    if not list_:
        raise ValueError('Empty list')
    if len(list_) == 1:           
        raise ValueError('Single-element list')
    value_to_count_dict: typing.DefaultDict[float, int] = collections.defaultdict(int)
    for element in list_:
        value_to_count_dict[element] += 1
    count_to_values_dict = collections.defaultdict(list)
    for value, count in value_to_count_dict.items():   
        count_to_values_dict[count].append(value)                           
    counts = list(count_to_values_dict)
    if len(counts) == 1:                                                                            
        raise ValueError('All elements in list are the same')          
    maximum_occurrence_count = max(counts)
    if maximum_occurrence_count == 1:
        raise ValueError('No element occurs more than once')
    minimum_occurrence_count = min(counts)
    if maximum_occurrence_count <= minimum_occurrence_count:
        raise ValueError('Maximum count not greater than minimum count')
    return count_to_values_dict[maximum_occurrence_count]

0
def mode(inp_list):
    sort_list = sorted(inp_list)
    dict1 = {}
    for i in sort_list:        
            count = sort_list.count(i)
            if i not in dict1.keys():
                dict1[i] = count

    maximum = 0 #no. of occurences
    max_key = -1 #element having the most occurences

    for key in dict1:
        if(dict1[key]>maximum):
            maximum = dict1[key]
            max_key = key 
        elif(dict1[key]==maximum):
            if(key<max_key):
                maximum = dict1[key]
                max_key = key

    return max_key

0
import numpy as np
def get_mode(xs):
    values, counts = np.unique(xs, return_counts=True)
    max_count_index = np.argmax(counts) #return the index with max value counts
    return values[max_count_index]
print(get_mode([1,7,2,5,3,3,8,3,2]))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接