查找列表的众数

2025-02-28 08:23:00
admin
原创
63
摘要:问题描述:给定一个项目列表,回想一下,列表的众数是最常出现的项目。我想知道如何创建一个函数,该函数可以找到列表的众数,但如果列表没有众数(例如,列表中的所有项目只出现一次),则显示一条消息。我想在不导入任何函数的情况下创建这个函数。我正在尝试从头开始创建自己的函数。解决方案 1:您可以使用max函数和键。查看...

问题描述:

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

我想知道如何创建一个函数,该函数可以找到列表的众数,但如果列表没有众数(例如,列表中的所有项目只出现一次),则显示一条消息。我想在不导入任何函数的情况下创建这个函数。我正在尝试从头开始创建自己的函数。


解决方案 1:

您可以使用max函数和键。查看使用“键”和 lambda 表达式的 python max 函数。

max(set(lst), key=lst.count)

解决方案 2:

您可以使用包Counter中提供collections的具有mode-esque 函数

from collections import Counter
data = Counter(your_list_in_here)
data.most_common()   # Returns all unique items and their counts
data.most_common(1)  # Returns the highest occurring item

注意:Counter 是 Python 2.7 中的新功能,在早期版本中不可用。

解决方案 3:

Python 3.4 包含方法statistics.mode,因此很简单:

>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
 3

列表中可以包含任何类型的元素,而不仅仅是数字:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
 'red'

解决方案 4:

借鉴一些统计软件,即SciPy和MATLAB,它们只返回最小的最常见值,因此如果两个值出现的频率相同,则返回其中最小的值。希望下面这个例子能有所帮助:

>>> from scipy.stats import mode

>>> mode([1, 2, 3, 4, 5])
(array([ 1.]), array([ 1.]))

>>> mode([1, 2, 2, 3, 3, 4, 5])
(array([ 2.]), array([ 2.]))

>>> mode([1, 2, 2, -3, -3, 4, 5])
(array([-3.]), array([ 2.]))

有什么理由你不能遵守这个惯例?

解决方案 5:

在 Python 中,有很多简单的方法可以查找列表的模式,例如:

import statistics
statistics.mode([1,2,3,3])
>>> 3

或者,你可以通过计数找到最大值

max(array, key = array.count)

这两种方法的问题在于它们不适用于多种模式。第一种方法返回错误,而第二种方法返回第一种模式。

为了找到集合的众数,可以使用以下函数:

def mode(array):
    most = max(list(map(array.count, array)))
    return list(set(filter(lambda x: array.count(x) == most, array)))

解决方案 6:

扩展社区答案,当列表为空时它将不起作用,这里是模式的工作代码:

def mode(arr):
        if arr==[]:
            return None
        else:
            return max(set(arr), key=arr.count)

解决方案 7:

如果您对最小、最大或所有模式感兴趣:

def get_small_mode(numbers, out_mode):
    counts = {k:numbers.count(k) for k in set(numbers)}
    modes = sorted(dict(filter(lambda x: x[1] == max(counts.values()), counts.items())).keys())
    if out_mode=='smallest':
        return modes[0]
    elif out_mode=='largest':
        return modes[-1]
    else:
        return modes

解决方案 8:

稍长一些,但可以有多种模式,并且可以获取具有大多数计数或混合数据类型的字符串。

def getmode(inplist):
    '''with list of items as input, returns mode
    '''
    dictofcounts = {}
    listofcounts = []
    for i in inplist:
        countofi = inplist.count(i) # count items for each item in list
        listofcounts.append(countofi) # add counts to list
        dictofcounts[i]=countofi # add counts and item in dict to get later
    maxcount = max(listofcounts) # get max count of items
    if maxcount ==1:
        print "There is no mode for this dataset, values occur only once"
    else:
        modelist = [] # if more than one mode, add to list to print out
        for key, item in dictofcounts.iteritems():
            if item ==maxcount: # get item from original list with most counts
                modelist.append(str(key))
        print "The mode(s) are:",' and '.join(modelist)
        return modelist 

解决方案 9:

数据集的众数是数据集中出现频率最高的成员。如果有两个成员出现频率最高且次数相同,则数据有两种众数。这称为双峰。

如果有超过 2 个众数,则该数据称为多众数。如果数据集中的所有成员出现的次数相同,则该数据集根本没有众数。 以下函数 modes() 可用于在给定的数据列表中查找模式:

import numpy as np; import pandas as pd

def modes(arr):
    df = pd.DataFrame(arr, columns=['Values'])
    dat = pd.crosstab(df['Values'], columns=['Freq'])
    if len(np.unique((dat['Freq']))) > 1:
        mode = list(dat.index[np.array(dat['Freq'] == max(dat['Freq']))])
        return mode
    else:
        print("There is NO mode in the data set")

输出:

# For a list of numbers in x as
In [1]: x = [2, 3, 4, 5, 7, 9, 8, 12, 2, 1, 1, 1, 3, 3, 2, 6, 12, 3, 7, 8, 9, 7, 12, 10, 10, 11, 12, 2]
In [2]: modes(x)
Out[2]: [2, 3, 12]
# For a list of repeated numbers in y as
In [3]: y = [2, 2, 3, 3, 4, 4, 10, 10]
In [4]: modes(y)
Out[4]: There is NO mode in the data set
# For a list of strings/characters in z as
In [5]: z = ['a', 'b', 'b', 'b', 'e', 'e', 'e', 'd', 'g', 'g', 'c', 'g', 'g', 'a', 'a', 'c', 'a']
In [6]: modes(z)
Out[6]: ['a', 'g']

如果我们不想导入numpypandas调用这些包中的任何函数,那么为了获得相同的输出,modes()函数可以写成:

def modes(arr):
    cnt = []
    for i in arr:
        cnt.append(arr.count(i))
    uniq_cnt = []
    for i in cnt:
        if i not in uniq_cnt:
            uniq_cnt.append(i)
    if len(uniq_cnt) > 1:
        m = []
        for i in list(range(len(cnt))):
            if cnt[i] == max(uniq_cnt):
                m.append(arr[i])
        mode = []
        for i in m:
            if i not in mode:
                mode.append(i)
        return mode
    else:
        print("There is NO mode in the data set")

解决方案 10:

我编写了这个方便的函数来查找模式。

def mode(nums):
    corresponding={}
    occurances=[]
    for i in nums:
            count = nums.count(i)
            corresponding.update({i:count})

    for i in corresponding:
            freq=corresponding[i]
            occurances.append(freq)

    maxFreq=max(occurances)

    keys=corresponding.keys()
    values=corresponding.values()

    index_v = values.index(maxFreq)
    global mode
    mode = keys[index_v]
    return mode

解决方案 11:

很短,但是有点丑:

def mode(arr) :
    m = max([arr.count(a) for a in arr])
    return [x for x in arr if arr.count(x) == m][0] if m>1 else None

使用字典,稍微不那么丑陋:

def mode(arr) :
    f = {}
    for a in arr : f[a] = f.get(a,0)+1
    m = max(f.values())
    t = [(x,f[x]) for x in f if f[x]==m]
    return m > 1 t[0][0] else None

解决方案 12:

此函数返回函数的众数(无论有多少),以及众数在数据集中的频率。如果没有众数(即所有项仅出现一次),则函数返回错误字符串。这与上面的 A_nagpal 函数类似,但在我看来,它更完整,而且我认为对于阅读此问题的任何 Python 新手(例如我本人)来说,它更容易理解。

 def l_mode(list_in):
    count_dict = {}
    for e in (list_in):   
        count = list_in.count(e)
        if e not in count_dict.keys():
            count_dict[e] = count
    max_count = 0 
    for key in count_dict: 
        if count_dict[key] >= max_count:
            max_count = count_dict[key]
    corr_keys = [] 
    for corr_key, count_value in count_dict.items():
        if count_dict[corr_key] == max_count:
            corr_keys.append(corr_key)
    if max_count == 1 and len(count_dict) != 1: 
        return 'There is no mode for this data set. All values occur only once.'
    else: 
        corr_keys = sorted(corr_keys)
        return corr_keys, max_count

解决方案 13:

对于一个数字来说mode,它出现的次数必须比列表中至少一个其他数字多,并且它不能是列表中唯一的数字。因此,我重构了@mathwizurd的答案(使用该difference方法),如下所示:

def mode(array):
    '''
    returns a set containing valid modes
    returns a message if no valid mode exists
      - when all numbers occur the same number of times
      - when only one number occurs in the list 
      - when no number occurs in the list 
    '''
    most = max(map(array.count, array)) if array else None
    mset = set(filter(lambda x: array.count(x) == most, array))
    return mset if set(array) - mset else "list does not have a mode!" 

这些测试成功通过:

mode([]) == None 
mode([1]) == None
mode([1, 1]) == None 
mode([1, 1, 2, 2]) == None 

解决方案 14:

您可以通过以下方法找到列表的平均值、中位数和众数:

import numpy as np
from scipy import stats

#to take input
size = int(input())
numbers = list(map(int, input().split()))

print(np.mean(numbers))
print(np.median(numbers))
print(int(stats.mode(numbers)[0]))

解决方案 15:

无需任何导入即可找到列表模式的简单代码:

nums = #your_list_goes_here
nums.sort()
counts = dict()
for i in nums:
    counts[i] = counts.get(i, 0) + 1
mode = max(counts, key=counts.get)

如果有多种模式,它应该返回最小节点。

解决方案 16:

我的大脑决定从头开始做这件事。高效而简洁 :)(开玩笑的,哈哈)

import random

def removeDuplicates(arr):
    dupFlag = False

    for i in range(len(arr)):
        #check if we found a dup, if so, stop
        if dupFlag:
            break

        for j in range(len(arr)):
            if ((arr[i] == arr[j]) and (i != j)):
                arr.remove(arr[j])
                dupFlag = True
                break;

    #if there was a duplicate repeat the process, this is so we can account for the changing length of the arr
    if (dupFlag):
        removeDuplicates(arr)
    else:
        #if no duplicates return the arr
        return arr

#currently returns modes and all there occurences... Need to handle dupes
def mode(arr):
    numCounts = []

    #init numCounts
    for i in range(len(arr)):
        numCounts += [0]

    for i in range(len(arr)):
        count = 1
        for j in range(len(arr)):
            if (arr[i] == arr[j] and i != j):
                count += 1
        #add the count for that number to the corresponding index
        numCounts[i] = count

    #find which has the greatest number of occurences
    greatestNum = 0
    for i in range(len(numCounts)):
        if (numCounts[i] > greatestNum):
            greatestNum = numCounts[i]

    #finally return the mode(s)
    modes = []
    for i in range(len(numCounts)):
        if numCounts[i] == greatestNum:
            modes += [arr[i]]
    
    #remove duplicates (using aliasing)
    print("modes: ", modes)
    removeDuplicates(modes)
    print("modes after removing duplicates: ", modes)
    
    return modes


def initArr(n):
    arr = []
    for i in range(n):
        arr += [random.randrange(0, n)]
    return arr

#initialize an array of random ints
arr = initArr(1000)
print(arr)
print("_______________________________________________")

modes = mode(arr)

#print result
print("Mode is: ", modes) if (len(modes) == 1) else print("Modes are: ", modes)

解决方案 17:

为什么不只是

def print_mode (thelist):
  counts = {}
  for item in thelist:
    counts [item] = counts.get (item, 0) + 1
  maxcount = 0
  maxitem = None
  for k, v in counts.items ():
    if v > maxcount:
      maxitem = k
      maxcount = v
  if maxcount == 1:
    print "All values only appear once"
  elif counts.values().count (maxcount) > 1:
    print "List has multiple modes"
  else:
    print "Mode of list:", maxitem

它没有一些应该有的错误检查,但它会在不导入任何函数的情况下找到模式,并且如果所有值只出现一次,则会打印一条消息。它还会检测共享相同最大计数的多个项目,尽管不清楚您是否想要这样做。

解决方案 18:

这将返回所有模式:

def mode(numbers)
    largestCount = 0
    modes = []
    for x in numbers:
        if x in modes:
            continue
        count = numbers.count(x)
        if count > largestCount:
            del modes[:]
            modes.append(x)
            largestCount = count
        elif count == largestCount:
            modes.append(x)
    return modes

解决方案 19:

对于那些寻找最小模式的人,例如双峰分布的情况,使用 numpy。

import numpy as np
mode = np.argmax(np.bincount(your_list))

解决方案 20:

好的!社区已经有很多答案,其中一些使用了另一个函数,而您不想要。

让我们创建非常简单且易于理解的函数。

import numpy as np

#Declare Function Name
def calculate_mode(lst):

下一步是在列表中找到唯一元素及其各自的频率

unique_elements,freq = np.unique(lst, return_counts=True)

获取模式

max_freq = np.max(freq)   #maximum frequency
mode_index = np.where(freq==max_freq)  #max freq index
mode = unique_elements[mode_index]   #get mode by index
return mode

例子

lst =np.array([1,1,2,3,4,4,4,5,6])
print(calculate_mode(lst))
>>> Output [4]

解决方案 21:

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

解决方案 22:

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])

解决方案 23:

这是一个获取列表中出现的第一个众数的简单函数。它创建一个字典,以列表元素为键,以出现次数为单位,然后读取字典值以获取众数。

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.")

解决方案 24:

如果您想要一种清晰的方法,适用于课堂并且仅通过理解使用列表和词典,您可以这样做:

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}

解决方案 25:

#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)

解决方案 26:

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]))

解决方案 27:

也许可以尝试以下方法。它是 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://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list
    """                                                                                                        
    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]
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2941  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1803  
  PLM(产品生命周期管理)系统在企业的产品研发、生产与管理过程中扮演着至关重要的角色。然而,在实际运行中,资源冲突是经常会遇到的难题。资源冲突可能导致项目进度延迟、成本增加以及产品质量下降等一系列问题,严重影响企业的效益与竞争力。因此,如何有效应对PLM系统中的资源冲突,成为众多企业关注的焦点。接下来,我们将详细探讨5...
plm项目管理系统   31  
  敏捷项目管理与产品生命周期管理(PLM)的融合,正成为企业在复杂多变的市场环境中提升研发效率、增强竞争力的关键举措。随着技术的飞速发展和市场需求的快速更迭,传统的研发流程面临着诸多挑战,而将敏捷项目管理理念融入PLM,有望在2025年实现研发流程的深度优化,为企业创造更大的价值。理解敏捷项目管理与PLM的核心概念敏捷项...
plm项目   31  
  模块化设计在现代产品开发中扮演着至关重要的角色,它能够提升产品开发效率、降低成本、增强产品的可维护性与可扩展性。而产品生命周期管理(PLM)系统作为整合产品全生命周期信息的关键平台,对模块化设计有着强大的支持能力。随着技术的不断发展,到 2025 年,PLM 系统在支持模块化设计方面将有一系列令人瞩目的技术实践。数字化...
plm软件   28  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用