python 找出序列中出现次数最多的元素方法

怎样找出一个序列中出现次数最多的元素呢?

1:超极简单的方法

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))
#OUT
# 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(4))
#OUT
# [('eyes', 8), ('the', 5), ('look', 4), ('into', 3)]

2:稍微复杂的

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'
]

dict_num = {}
for item in words:
    if item not in dict_num.keys():
        dict_num[item] = words.count(item)

print (dict_num)

# 未做排序
# {"you're": 1, 'eyes': 8, 'look': 4, "don't": 1, 'into': 3, 'under': 1, 'not': 1, 'the': 5, 'my': 3, 'around': 2}

# 排序
import operator
sorted(dict_num.items(),key=operator.itemgetter(1))

#OUT
#[('not', 1),("don't", 1),("you're", 1),('under', 1),('around', 2),('into', 3),('my', 3),('look', 4),('the', 5),('eyes', 8)]

3:字典推导

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'
]


dict_num = dict_num = {i:words.count(i) for i in set(words)}

4:字典setdefault

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'
    ]
d = dict()
for item in words:
    d[item] = d.setdefault(item,0) + 1
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 〇、前言 本文共108张图,流量党请慎重! 历时1个半月,我把自己学习Python基础知识的框架详细梳理了一遍。 ...
    Raxxie阅读 19,268评论 17 410
  • 事件一: 最近PGOne的事情在网上闹得沸沸扬扬,先是被爆出不清不楚的人际关系,紧接着又扒出他之前所唱的一首歌,歌...
    芸的思考阅读 3,712评论 2 1
  • 总结昨天写了,今天怎么也想不到更多的,可能因为这次千字计划几乎毫无规划,甚至没有目标,只是想虐一虐自己。真的有虐到...
    斯卓poppy阅读 1,651评论 0 0
  • 文/小喵1/52周回顾 第一次进行的每周回顾,这个星期的任务基本都完成了,不过效果并不是100%,因为我刚刚知道,...
    迷妹乔小喵阅读 2,875评论 0 0
  • 昨晚刚刚读完了《The Martian》的原版,电影之前也看过,总的来说电影和书都不错,那种诙谐的风格字里行间都透...
    七月聊聊阅读 5,604评论 0 0