栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何找到列表中最常见的元素?[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何找到列表中最常见的元素?[重复]

如果您使用的是Python的早期版本,或者您有充分的理由推出自己的单词计数器(我想听听它!),则可以尝试使用以下方法

dict

Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> word_list = ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cats', 'have', 'bright', 'black', 'eyes;', 'They', 'like', 'to', 'practise', 'their', 'airs', 'and', 'graces', 'And', 'wait', 'for', 'the', 'Jellicle', 'Moon', 'to', 'rise.', '']>>> word_counter = {}>>> for word in word_list:...     if word in word_counter:...         word_counter[word] += 1...     else:...         word_counter[word] = 1... >>> popular_words = sorted(word_counter, key = word_counter.get, reverse = True)>>> >>> top_3 = popular_words[:3]>>> >>> top_3['Jellicle', 'Cats', 'and']

热门提示 :每当您要使用这样的算法时,交互式Python解释器就是您的朋友。只需将其键入并观看,然后检查整个过程中的元素。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380439.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号