python cookbook 学习笔记 第一章 数据结构和算法(11)序列中出现次数最多的元素

  • 序列中出现次数最多的元素
  • 问题
    • 怎样找出一个序列中出现次数最多的元素呢?
  • 解决方案:
    • collections.Counter 类就是专门为这类问题而设计的,它甚至有一个有用的most.common()方法 直接给了你答案。
      -为了演示,先假设有一个单词列表并且想找出哪个单词出现频率最高。可以这样做:
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'
]

from collections import Counter

word_counters = Counter(words)
top_three = word_counters.most_common(3)
print(top_three)    # [('eyes', 8), ('the', 5), ('look', 4)]
  • 讨论: 作为输入,Counter 对象可以接受任意的 hashable 序列对象。在底层实现上,一个Counter 对象 就是一个字典,将元素映射到他出现的次数上。比如:
print(word_counters["not"])  # 1
print(word_counters["eyes"]) # 8
  • 如果你想手动增加计数,可以简单的用加法:
morewords = ["why", "are", "you", "not", "looking", "in", "my", "eyes"]

for word in morewords:
    word_counters[word] += 1
print(word_counters["eyes"])  # 9
  • 或者可以使用 update()方法:
word_counters.update(morewords)  # 和上面的演示效果一样
  • Counter 实例另一个特性是他们可以很容易的跟数学运算操作结合。比如:
a = Counter(words)
b = Counter(morewords)
c = a + b
print(c)
d = a - b
print(d)
  • 毫无疑问,Counter 对象在几乎所有需要值班或者计数数据的场合是非常有用的工具,在解决这类问题的时候 应该有些选择它,而不是手动利用字典去实现。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值