在 Python 中查找列表中最常见元素的方法
    
    
            Najwa Riyaz
    2023年10月10日
    
    Python
    Python List
    
- 
          
            在 Python 中使用 Counter的most_common()查找列表中最常见的元素
- 
          
            在 Python 中使用 FreqDist()的max()函数查找列表中最常见的元素
- 
          
            在 Python 中使用 NumPy的unique()函数查找列表中最常见的元素
 
本文提到了在 Python 中查找列表中最常见元素的几种方法。以下是我们可以用来查找 Python 中最常见列表元素的函数。
- 使用 Counter的most_common()函数。
- 使用 FreqDist()的max()函数。
- 使用 NumPy的unique()函数。
在 Python 中使用 Counter 的 most_common() 查找列表中最常见的元素
在 Python 2.7+ 中,使用 Counter() 命令来查找 Python 中最常见的列表元素。为此,你需要从 collections 标准库中导入 Counter 类。
Counter 是一个集合,其中元素存储为字典键,键的计数存储为字典值。下面的例子说明了这一点。
from collections import Counter
list_of_words = ["Cars", "Cats", "Flowers", "Cats", "Cats", "Cats"]
c = Counter(list_of_words)
c.most_common(1)
print("", c.most_common(1))
这里,最上面的一个元素是通过使用 most_common() 函数作为 most_common(1) 来确定的。
输出:
[('Cats', 4)]
在 Python 中使用 FreqDist() 的 max() 函数查找列表中最常见的元素
你还可以使用 FreqDist() 的 max() 命令来查找 Python 中最常见的列表元素。为此,你首先导入 nltk 库。下面的示例演示了这一点。
import nltk
list_of_words = ["Cars", "Cats", "Flowers", "Cats"]
frequency_distribution = nltk.FreqDist(list_of_words)
print("The Frequency distribution is -", frequency_distribution)
most_common_element = frequency_distribution.max()
print("The most common element is -", most_common_element)
在这里,首先使用 FreqDist() 函数构建频率分布列表,然后使用 max() 函数确定最常见的元素。
输出:
The Frequency distribution is - <FreqDist with 3 samples and 4 outcomes>
The most common element is - Cats
在 Python 中使用 NumPy 的 unique() 函数查找列表中最常见的元素
最后,你可以使用 NumPy 库的 unique() 函数在 Python 中查找列表中最常见的元素。下面的示例说明了这一点。
import numpy
list_of_words = [
    "Cars",
    "Cats",
    "Flowers",
    "Cats",
    "Horses",
    "",
    "Horses",
    "Horses",
    "Horses",
]
fdist = dict(zip(*numpy.unique(list_of_words, return_counts=True)))
print("The elements with their counts are -", fdist)
print("The most common word is -", list(fdist)[-1])
此操作的输出是键值对字典,其中值是特定单词的计数。使用 unique() 函数查找数组的唯一元素。接下来,zip() 命令用于映射多个容器的相似索引。在本例中,我们使用它来获取频率分布。由于输出按升序列出键值对,因此最常见的元素由最后一个元素决定。
输出:
The elements with their counts are - {'': 1, 'Cars': 1, 'Cats': 2, 'Flowers': 1, 'Horses': 4}
The most common word is - Horses
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe