python统计数组中出现次数最多的元素

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

方法1-np.argmax(np.bincount())
array = [0,1,2,2,3,4,4,4,5,6]
print(np.bincount(array))
#[1 1 2 1 3 1 1]
print(np.argmax(np.bincount(array)))
#4

np.argmax:就是返回数组中最大值对应的下标,
np.bincount:首先找到数组最大值max,然后返回0~max的各个数字出现的次数,只能处理不含负数的集合

方法2-Counter().most_common

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

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


from collections import Counter
array = [0,1,2,2,3,4,4,4,5,6,'aswd']
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, 'aswd': 1})
#4
方法三-- 自己数各个元素出现的次数然后找到出现次数最多的元素

appear_times = {}
for label in [1,1,2,3,4,5,5,5]:
    if label in appear_times:
      appear_times[label] += 1
    else:
      appear_times[label] = 1

most_common = max(appear_times, key=lambda x: appear_times[x])
print(appear_times)
print(most_common)

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

这里需要注意的是appear_times是一个列表,用max求最大值默认情况返回value值(出现次数)最大的key值(元素),而不是value值,这里max函数中的参数key(和前面说的key不是一个东西)是指定寻找最大值的方式,在我们这个问题这里其实不需要这个参数,不过为了便于理解我还是写上了,对max函数key参数更深入的理解可以参考下面的例子:
复制代码


print(max('ahecsc', 'bfsacg', 'aaaaaz', key=lambda x: x[0]))
print(max('ahecsc', 'bfsacg', 'aaaaaz', key=lambda x: x[3]))
print(max('ahecsc', 'bfsacg', 'aaaaaz', key=lambda x: x[5]))

#bfsacg
#ahecsc
#aaaaaz

同样的数据,key参数不同,结果不同,第一种情况是以数据的第一个位置元素的大小关系排序,并返回排序结果最大的数据(‘b’>‘a’>‘a’,返回’b’所在的’bfsacg’);第二种情况类似(‘c’>‘a’>‘a’,返回’c’所在的’ahecsc’);第三种情况(‘z’>‘g’>‘c’,返回’z’所在的’aaaaaz’)

文章转载出处:https://www.cnblogs.com/RB26DETT/p/11518589.html

  • 12
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值