Python找出列表中出现次数最多的元素三种方式

您所在的位置:网站首页 python空函数 Python找出列表中出现次数最多的元素三种方式

Python找出列表中出现次数最多的元素三种方式

2023-04-14 05:19| 来源: 网络整理| 查看: 265

通过三种方式给大家介绍,具体详情如下所示:

方式一:

原理:创建一个新的空字典,用循环的方式来获取列表中的每一个元素,判断获取的元素是否存在字典中的key,如果不存在的话,将元素作为key,值为列表中元素的count

# 字典方法 words = [ 'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I', 'need', 'skills', 'more', 'my', 'ability', 'are', 'so', 'poor' ] dict1 = {} for i in words: if i not in dict1.keys(): dict1[i] = words.count(i) print(dict1)

运行结果:

{‘my’: 2, ‘skills’: 2, ‘are’: 2, ‘poor’: 3, ‘I’: 2, ‘am’: 1, ‘need’: 1, ‘more’: 1, ‘ability’: 1, ‘so’: 1}

方式二

原理:使用setdefault函数,setdefault()函数,如果键不存在于字典中,将会添加键并将值设为默认值。 打个比方,我们要查找的这个键不在字典中,我们先将它置为0,然后再加1,再查找到这个键的时候,这个时候它是存在这个字典里面的,故这个setdefault函数不生效,然后我们再把次数加1

words = [ 'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I', 'need', 'skills', 'more', 'my', 'ability', 'are', 'so', 'poor' ] d = dict() for item in words: # setdefault()函数,如果键不存在于字典中,将会添加键并将值设为默认值 d[item] = d.setdefault(item, 0) + 1 print(d)

运行结果:

{‘my’: 2, ‘skills’: 2, ‘are’: 2, ‘poor’: 3, ‘I’: 2, ‘am’: 1, ‘need’: 1, ‘more’: 1, ‘ability’: 1, ‘so’: 1}

方式三

原理:使用collections模块的Counter类 这个模块很强大,尤其是这个类。他可以直接帮我们计数,然后再帮我们排序好。从大到小

from collections import Counter words = [ 'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I', 'need', 'skills', 'more', 'my', 'ability', 'are', 'so', 'poor' ] collection_words = Counter(words) print(collection_words) print(type(collection_words))

运行结果:

Counter({‘poor’: 3, ‘my’: 2, ‘skills’: 2, ‘are’: 2, ‘I’: 2, ‘am’: 1, ‘need’: 1, ‘more’: 1, ‘ability’: 1, ‘so’: 1})



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3