開始使用免費開始

找出最常見的元素

Counter 的另一個強大用法,是找出串列中最常見的元素。你可以用 .most_common() 方法達成。

現在來練習用它,從一個企鵝(penguins)串列中找出最常見的物種。

本練習屬於課程

Python 的資料型別

檢視課程

練習說明

  • collections 匯入 Counter 物件。
  • 針對 penguins 串列建立一個名為 penguins_species_countsCounter;使用串列生成式將每隻企鵝的 Species 傳回給 Counter。
  • 列印出最常見的三個物種及其次數。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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(____)
編輯並執行程式碼