python查找数组中出现次数最多的元素

问题:找出数组中出现次数最多的元素。

方法1:

关于set(),max()及排序用法详见https://blog.csdn.net/guo_qingxia/article/details/103480106和https://blog.csdn.net/guo_qingxia/article/details/115409366

list = ['1', '2', '3', '6', '5', '6', '6', '2', '1']
result = max(set(list), key=list.count)
print(result)

结果:6

  延伸问题:统计数组中每个元素出现的次数。

List = [1,2,3,4,5,3,2,1,4,5,6,4,2,3,4,6,2,2]
List_set = set(List)
print(List_set)
for item in List_set:
    print("the %d has found %d" % (item, List.count(item)))

结果:

{1, 2, 3, 4, 5, 6}
the 1 has found 2
the 2 has found 5
the 3 has found 3
the 4 has found 4
the 5 has found 2
the 6 has found 2

或者 自己数各个元素出现的次数,然后找到出现次数最多的元素。max求最大值默认情况返回value值(出现次数)最大的key值(元素),而不是value值

appear_times = {}
list = [1,1,2,3,4,5,5,5]
for lable in list:
    if lable in appear_times:
        appear_times[lable] += 1
    else:
        appear_times[lable] = 1
most_common = max(appear_times, key=lambda x: appear_times[x])#或most_common = max(appear_times)
print(appear_times)
print(most_common)

结果:

{1: 2, 2: 1, 3: 1, 4: 1, 5: 3}

方法2:

使用numpy库

np.bincount():计算非负整数数组中每个值的出现次数(统计0~max出现的次数)。语法:numpy.bincount(x, weights=None, minlength=None)。

np.argmax:返回的是最大数的索引

import numpy as np
array = [0,1,2,2,3,4,4,4,5,6]
#np.bincount:首先找到数组最大值max,然后返回0~max的各个数字出现的次数,在上例中,0出现了1次,1出现了1次,2出现了2次...以此类推。np.bincount返回的数组中的下标对应的就是原数组的元素值。
print(np.bincount(array))
#np.argmax:返回数组中最大值对应的下标
print(np.argmax(np.bincount(array)))

结果:

[1 1 2 1 3 1 1]
4

方法3:

Counter用来对数组中元素出现次数进行统计,然后通过most_common函数找到出现次数最多的元素。这种方法对于数组就没有过多限制,甚至是各种类型元素混合的数组也可以。

from collections import Counter
array = [0,1,2,2,3,4,4,4,5,6]
print(Counter(array))
print(Counter(array).most_common(1)[0][0])

结果:

Counter({4: 3, 2: 2, 0: 1, 1: 1, 3: 1, 5: 1, 6: 1})
4

 

你可能感兴趣的:(python)