Подтвердить что ты не робот

Поиск режима списка

Учитывая список элементов, напомните, что режим списка - это элемент, который чаще всего встречается.

Я хотел бы знать, как создать функцию, которая может найти режим списка, но который отображает сообщение, если в списке нет режима (например, все элементы в списке появляются только один раз). Я хочу сделать эту функцию без импорта каких-либо функций. Я пытаюсь сделать свою собственную функцию с нуля.

4b9b3361

Ответ 2

Вы можете использовать Counter в пакете collections, который имеет mode -образная функция

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

Примечание. Счетчик является новым в 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 по его счету

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

Ответ 9

Короче, но как-то уродливо:

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

Ответ 10

Немного дольше, но может иметь несколько режимов и может получать строку с большим количеством подсчетов или комбинацией типов данных.

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 

Ответ 11

Почему не просто

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

У этого нет нескольких проверок ошибок, которые он должен иметь, но он найдет режим без импорта каких-либо функций и распечатает сообщение, если все значения появятся только один раз. Он также обнаружит несколько элементов, имеющих один и тот же максимальный счет, хотя было неясно, хотите ли вы этого.

Ответ 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

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

Ответ 16

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

Ответ 17

Вот простая функция, которая получает первый режим, который встречается в списке. Он делает словарь с элементами списка как ключи и количество вхождений, а затем считывает значения dict для получения режима.

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

Ответ 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

Если вы хотите четкий подход, полезный для аудитории и использующий только списки и словари по пониманию, вы можете сделать:

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}

Ответ 20

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

Ответ 21

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