Python找出列表中出现次数最多的元素

方式一:

原理:创建一个新的空字典,用循环的方式来获取列表中的每一个元素,判断获取的元素是否存在字典中的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})
<class 'collections.Counter'>

还可以输出频率最大的n个元素,类型为list

most_counterNum = collection_words.most_common(3)
print(most_counterNum)
print(type(most_counterNum))

运行结果:

[('poor', 3), ('my', 2), ('skills', 2)]
<class 'list'>

ounter类支持collections.Counter类型的相加和相减
也就是用Counter(words)之后,这个类型是可以相加减的,只支持相加减
例子:

print(collection_words + collection_words)

这里要注意:不能为了图方便进行collection_words * 2,因为类型不同,2int,故不能进行运算
运行结果:

Counter({'poor': 6, 'my': 4, 'skills': 4, 'are': 4, 'I': 4, 'am': 2, 'need': 2, 'more': 2, 'ability': 2, 'so': 2})

如果笔者有其他的方法,会慢慢往文章里面填写,感谢

发布了17 篇原创文章 · 获赞 7 · 访问量 731

猜你喜欢

转载自blog.csdn.net/qq_44168690/article/details/104447527
今日推荐