我有一个有93个不同字符串的列表。我需要找到10个最频繁的字符串,返回的顺序必须是从最频繁到最不频繁。
mylist = ['"and', '"beware', '`twas', 'all', 'all', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'arms', 'as', 'as', 'awhile', 'back', 'bandersnatch', 'beamish', 'beware', 'bird', 'bite', 'blade', 'borogoves', 'borogoves', 'boy', 'brillig']
# this is just a sample of the actual list.
我没有最新版本的python,不能使用计数器。
不使用
Counter
作为问题请求的修改版本已更改为使用@Duncan建议的
heap.nlargest
David的答案是最好的——但是如果您使用的Python版本不包括collections模块(在Python 2.7中引入)中的Counter,那么您可以使用做相同事情的Counter类的this implementation。我怀疑它会比模块慢,但会做同样的事情。
您可以使用^{} module 中的^{} 来执行此操作。
然后执行
c.most_common(10)
返回相关问题 更多 >
编程相关推荐