开始使用免费开始使用

查找最常见的元素

Counter 的另一个强大用法是查找列表中最常见的元素。这可以通过 .most_common() 方法完成。

现在来练习一下:在一个企鹅列表中找出最常见的物种。

本练习是课程的一部分

Python 的数据类型

查看课程

练习说明

  • collections 导入 Counter 对象。
  • penguins 列表创建一个名为 penguins_species_countsCounter;使用列表推导式将每只企鹅的 Species 返回给 Counter。
  • 打印出现次数最多的 3 个物种及其计数。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import the Counter object
____

# Create a Counter of the penguins list: penguins_species_counts
penguins_species_counts = ____

# Find the 3 most common species counts
print(____)
编辑并运行代码