《Python Cookbook(第3版)中文版》——1.12 找出序列中出现次数最多的元素

简介:

本节书摘来自异步社区《Python Cookbook(第3版)中文版》一书中的第1章,第1.12节,作者[美]David Beazley , Brian K.Jones,陈舸 译,更多章节内容可以访问云栖社区“异步社区”公众号查看。

1.12 找出序列中出现次数最多的元素

1.12.1 问题

我们有一个元素序列,想知道在序列中出现次数最多的元素是什么。

1.12.2 解决方案

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_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]

1.12.3 讨论

可以给Counter对象提供任何可哈希的对象序列作为输入。在底层实现中,Counter是一个字典,在元素和它们出现的次数间做了映射。例如:

>>> word_counts['not']
1
>>> word_counts['eyes']
8
>>>

如果想手动增加计数,只需简单地自增即可:

>>> morewords = ['why','are','you','not','looking','in','my','eyes']
>>> for word in morewords:
... word_counts[word] += 1
...
>>> word_counts['eyes']
9
>>>

另一种方式是使用update()方法。

>>> word_counts.update(morewords)
>>>

关于Counter对象有一个不为人知的特性,那就是它们可以轻松地同各种数学运算操作结合起来使用。例如:

>>> a = Counter(words)
>>> b = Counter(morewords)
>>> a
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,
         "you're": 1, "don't": 1, 'under': 1, 'not': 1})
>>> b
Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,
         'my': 1, 'why': 1})

>>> # Combine counts
>>> c = a + b
>>> c
Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2,
         'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1,
         'looking': 1, 'are': 1, 'under': 1, 'you': 1})

>>> # Subtract counts
>>> d = a - b
>>> d
Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,
         "you're": 1, "don't": 1, 'under': 1})
>>>

不用说,当面对任何需要对数据制表或计数的问题时,Counter对象都是你手边的得力工具。比起利用字典自己手写算法,更应该采用这种方式完成任务。

相关文章
|
5月前
|
Python
Python 选出列表中特定的元素
Python 选出列表中特定的元素
68 3
|
5月前
|
数据处理 索引 Python
Python列表与元素修改的操作技巧
Python列表提供了丰富的方法和技巧来进行高效的数据操作。熟练运用上述技巧,可以大大提高数据处理的效率和代码的可读性。实践中,根据具体需求灵活选择合适的方法,可以在保证代码效率的同时,也使代码更加简洁明了。
119 2
|
6月前
|
程序员 Python
Python 将元素添加到列表
【8月更文挑战第21天】
266 3
|
6月前
|
Python
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
python在列表、元素、字典、集合和numpy的数组前加上星号 * 是什么含义,以及*args和**kwargs的使用
72 0
|
4月前
|
存储 C++ 索引
Python 序列类型(1)
【10月更文挑战第8天】
|
4月前
|
存储 编译器 索引
Python 序列类型(2)
【10月更文挑战第8天】
Python 序列类型(2)
|
6月前
|
存储 索引 Python
Python中序列类型 (Sequence Types)
【8月更文挑战第2天】
116 4
|
存储 算法 BI
【100天精通python】Day6:python基础_基本数据结构,常用序列类型和运算符
【100天精通python】Day6:python基础_基本数据结构,常用序列类型和运算符
145 0
|
Java 索引 Python
【Python】序列类型①-列表
序列是一块用来存放多个值的内存空间.Python中常用的数据结构有列表,元组,字典,字符串,集合等. 本篇文章主要讲解列表的常见操作.
【Python】序列类型②-元组
元组和列表一样可以存放多个,不同数据类型的元素 与列表最大的不同就是:列表是可变的,而元组不可变

热门文章

最新文章