字符串组中统计出现次数最大的-python

本文介绍了一种使用Python的collections库中的Counter类来统计一个字符串数组中各字符串出现次数的方法,并展示了如何找出出现次数最多的字符串。

  一个字符串组成的大数组,统计里面出现次数最大的字符串,并输出,两种方式:

from collections import Counter

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
]

print Counter(words)
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, "you're": 1, "don't": 1, 'under': 1, 'not': 1})

print Counter(words).most_common(3)
[('eyes', 8), ('the', 5), ('look', 4)]      # 次数最大的三个



import numpy

Counter(words).values()
Out[26]: [1, 8, 4, 1, 3, 1, 1, 5, 3, 2]


m=numpy.argmax(Counter(words).values())       # 注意字典的使用,如何输出所有的键,如何输出所有的键值  如何返回最大的那个的下角标

m
Out[31]: 1

print Counter(words).keys()[m]
eyes


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值