我试图获取数组中最频繁的两个元素的数量。例如,在列表['aa','bb','cc','dd','bb','bb','cc','ff']
中,最常出现的次数应该是3
(数组中出现“ bb”的次数),而第二常出现的次数应该是(数组中2
出现“ cc”的次数)。
我尝试了这个:
max = 0
snd_max = 0
for i in x:
aux=x.count(i)
if aux > max
snd_max=max
max=aux
print(max, snd_max)
但是我怀疑是否有更简单的方法?
您可以使用collections.Counter
:
from collections import Counter
x = ['aa','bb','cc','dd','bb','bb','cc','ff']
counter = Counter(x)
print(counter.most_common(2))
[('bb',3),('cc',2)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句