2015-03-20 2 views
-1
dictionary={} 
list=[1,1,2,3,3,4,5] 
maximum=0 
for values in list: 
    if values in dictionary: 
     dictionary[values]+=1 
    else: 
     dictionary[values]=1 
if not maximum or dictionary[values]>maximum[0]: 
maximum=(values,dictionary[values]) 
mode=maximum[0] 
print("Mode:",mode) 

Выход: 3Найти режим списка чисел в Python

Вывод должен быть 1 и 3, так как происходит дважды.

+2

'collections.Counter ([1,1,2,3,3,4,5])' –

ответ

1

Вы в основном заново изобретаете встроенный collections.Counter.

In [3]: my_list = [1, 1, 2, 3, 3, 4, 5] 

In [4]: from collections import Counter 

In [5]: counter = Counter(my_list) 

In [6]: max_count = max(counter.values()) 

In [7]: mode = [k for k,v in counter.items() if v == max_count] 

In [8]: mode 
Out[8]: [1, 3] 

Edit:

питон 3 делает поддержку statistics.mode; однако в вашем списке возникает ошибка, так как не существует уникального режима.

1

Вы можете использовать scipy получить mode

>>> from scipy.stats import mode 

>>> mode(alist) 
1
# Function to return all modes, this function takes into account multimodal distributions. 
# Function returns all modes as list or 'NA' if such value doesn't exist. 
def mode(l): 
    if len(l) > 1: # 
     #Creates dictionary of values in l and their count 
     d = {} 
     for value in l: 
      if value not in d: 
       d[value] = 1 
      else: 
       d[value] += 1 

     if len(d) == 1: 
      return [value] 
     else: 
      # Finds most common value 
      i = 0 
      for value in d: 
       if i < d[value]: 
        i = d[value] 

      # All values with greatest number of occurrences can be a mode if: 
      # other values with less number of occurrences exist 
      modes = [] 
      counter = 0 
      for value in d: 
       if d[value] == i: 
        mode = (value, i) 
        modes.append(mode) 
        counter += mode[1] # Create the counter that sums the number of most common occurrences 

      # Example [1, 2, 2, 3, 3] 
      # 2 appears twice, 3 appears twice, [2, 3] are a mode 
      # because sum of counter for them: 2+2 != 5 
      if counter != len(l): 
       return [mode[0] for mode in modes] 
      else: 
       return 'NA' 
    else: 
     return l 

l1 = [1] 
l2 = [1, 1] 
l3 = [1, 1, 2, 2] 
l4 = [1, 2, 3, 4, 5] 
l5 = [1, 1, 2, 2, 3, 3, 4] 
l6 = [1, 2, 3, 4, 4] 
l7 = ['string', 'string', 1] 
l8 = ['string', 'string', 1, 1, 1] 

print mode(l1) 
print mode(l2) 
print mode(l3) 
print mode(l4) 
print mode(l5) 
print mode(l6) 
print mode(l7) 
print mode(l8) 
Смежные вопросы