一个字符串组成的大数组,统计里面出现次数最大的字符串,并输出,两种方式:
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

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

被折叠的 条评论
为什么被折叠?



