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)}
  • 11
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值