如何找到Python字典中最常见的元素

135 阅读4分钟

问题的提出和解决方案概述

这篇文章将告诉你如何在Python字典中找到最常见的元素。然而,由于所有的Dictionary键都是唯一的,这篇文章的重点是搜索最常见的Dictionary值。

为了使它更有趣,我们有以下运行场景。

Harwood高中的数学老师Marty Smart收集了他的学生本学期的成绩,他来找你写一个脚本来确定最常见的成绩。以下是样本数据。

students = {'Marc': 99, 'Amie': 76, 'Jonny': 98, 'Anne': 99,
            'Andy': 77, 'Elli': 98, 'Acer': 67, 'Joan': 61,
            'Mike': 54, 'Anna': 76, 'Bobi': 67, 'Kate': 99,
            'Todd': 98, 'Emma': 49, 'Stan': 76, 'Harv': 99,
            'Ward': 67, 'Hank': 54, 'Wendy': 98, 'Sven': 100}

💬 问题 :我们如何编写代码来定位一个字典中最常见的值?

我们可以通过以下方法之一来完成这项任务。

  • 方法1 :使用 [statistics.mode()](https://docs.python.org/3/library/statistics.html)
  • 方法2 :使用 collections.Counter
  • 方法3 :使用 [for](https://blog.finxter.com/python-loops/)循环和 max()
  • 方法4:使用 max()

方法1:使用统计学模式()

这个例子使用 mode()statistics库。这个函数返回在传递的参数中发现的最常见的单一元素。

from statistics import mode
common_val = mode(students.values())

上面的代码调用了 mode()从统计库中调用。

下面一行使用 mode()函数,并将studentskey:value对中的作为参数传递。结果保存到common_val

如果将students.values() 的内容输出到终端,将显示如下。

print(students.values())
dict_values([99, 76, 98, 99, 77, 98, 67, 61, 54, 76, 67, 99, 98, 49, 76, 99, 67, 54, 98, 100])

运行下面的代码来找到最常见的值。

print(common_val)
99

这就是正确的!


方法2:使用Collections.Counter

这个例子使用了 collections库和 counter()函数来跟踪每个元素的数量。

from collections import Counter 
common_val = Counter(students.values()).most_common

上面的代码导入了Python的内置 collections库和 counter().

接下来,该 counter()函数被调用,并将studentskey:value对中的所有作为一个参数传给它。 然后。 most_common()被追加。结果保存在common_val

如果把这个内容输出到终端,会显示以下内容。

<bound method Counter.most_common of Counter({99: 4, 98: 4, 76: 3, 67: 3, 54: 2, 77: 1, 61: 1, 49: 1, 100: 1})>

这并不是我们想要的结果。我们怎样才能得到这个结果呢?

common_val = Counter(students.values()).most_common(1) 

如果我们在most_common的末尾加上一个(1),就会返回一个包含一个TupleList

[(99, 4)]

为了进一步提取数据,使用切片([0]) )来引用Tuple,并对输出进行相应的分配。

value, count = Counter(students.values()).most_common(1)[0]
print(value, count)

清楚多了!这是个很好的例子。99这个等级在students 中出现了4次。

99 4

方法3:使用For Loop和max()

这个例子在一个字典中使用一个 [for](https://blog.finxter.com/python-loops/)循环和 max()不导入一个库。

tally = {}
for k, v in students.items():
    if v not in tally:
        tally[v] = 0
    else:
        tally[v] += 1
print(max(tally, key=tally.get))

上面的代码声明了一个空的字典 tally

然后一个 [for](https://blog.finxter.com/python-loops/)循环被实例化以循环浏览字典中的每个键:值students

如果v (值)不在tally ,那么for的计数被设置为0。

否则,如果tv (值)在tally中,则计数增加1。

循环完成后,调用 max()函数被调用以获得tally 中最常见的值并输出到终端。

99

方法4:使用max()

这个例子使用 max()来检索 Python 字典中最常见的值。简单、干净、高效。

common_val = max(list(students.values()), key=list(students.values()).count)

上面的代码调用 max()函数,并传递两(2)个参数,即studentskey:value对的值和一个 [List](https://blog.finxter.com/python-lists/) 对象。

如果输出到终端,这两(2)个参数包含以下内容。

print(list(students.values()))
print(list(students.values()).count)
[99, 76, 98, 99, 77, 98, 67, 61, 54, 76, 67, 99, 98, 49, 76, 99, 67, 54, 98, 100]
<built-in method count of list object at 0x00000239566D3540>

要检索最常见的元素,请运行以下代码。

print(common_val)
99

总结

这篇文章提供了(4)种方法来寻找Python字典中最常见的元素。这些例子应该给你足够的信息来选择最适合你编码要求的方法。

祝您好运,编码愉快!