找出最常見的元素
Counter 的另一個強大用法,是找出串列中最常見的元素。你可以用 .most_common() 方法達成。
現在來練習用它,從一個企鵝(penguins)串列中找出最常見的物種。
本練習屬於課程
Python 的資料型別
練習說明
- 從
collections匯入Counter物件。 - 針對
penguins串列建立一個名為penguins_species_counts的Counter;使用串列生成式將每隻企鵝的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(____)