在python中找到数字列表的模式

时间:2015-03-20 04:04:19

标签: python python-3.x

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

输出应为1和3,因为两者都出现两次。

4 个答案:

答案 0 :(得分:2)

您基本上正在重新发明内置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]

编辑:

python 3支持statistics.mode;但是,列表中会出现错误,因为不存在唯一模式。

答案 1 :(得分:1)

您可以使用scipy获取mode

>>> from scipy.stats import mode

>>> mode(alist)

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

答案 3 :(得分:0)

寻找模式的另一种方式

def mode(lst):
    d = {}
    for a in lst:
        if not a in d:
            d[a]=1
        else:
            d[a]+=1
    return [k for k,v in d.items() if v==max(d.values())]