如何在 Python 列表中統計某個物件的出現次數?
列表是 Python 提供的最常用資料結構之一。列表是 Python 中一種可變的資料結構,它包含一系列有序的元素。以下是一個整數列表的例子:
示例
以下是一個整數列表。
lis= [1,2,7,5,9,1,4,8,10,1] print(lis)
輸出
如果執行以上程式碼片段,則會產生以下輸出。
[1, 2, 7, 5, 9, 1, 4, 8, 10, 1]
在本文中,我們將討論如何在 Python 中查詢列表中某個物件出現的總次數。對於以上示例,數字 1 出現了 3 次。
Python 包含幾種方法來統計列表項出現的次數。
使用迴圈
在這種方法中,我們使用傳統方法,迭代迴圈並使用計數器變數來統計專案的出現次數。
示例
在以下示例中,我們從使用者處獲取輸入,並統計所需元素的出現次數。
def count_occurrence(lst, x): count = 0 for item in lst: if (item == x): count = count + 1 return count lst =[] n = int(input("Enter number of elements and the elements: ")) for i in range(n): item = int(input()) lst.append(item) x = int(input("Enter the number whose count you want to find in the list: ")) y = count_occurrence(lst,x) print('The element %s appears %s times in the list'%(x,y))
輸出
以上程式碼的輸出如下。
Enter number of elements and the elements: 8 2 4 1 3 2 5 2 9 Enter the number whose count you want to find in the list: 2 The element 2 appears 3 times in the list
使用列表 count() 方法
count() 方法計算元素在列表中出現的次數。在這種方法中,我們使用 Python 的 count() 方法來統計列表中某個元素的出現次數。此方法計算給定列表元素的總出現次數。
語法
count() 方法的語法如下所示。
list.count(ele)
其中,ele 是要計數的元素。
示例
在以下示例中,我們使用 count() 方法統計母音列表中 'i' 出現的次數。
vowels = ['a', 'e', 'i', 'o', 'i', 'u', 'i', 'o', 'e', 'a'] count = vowels.count('i') print("The count is" ,count)
輸出
以上程式碼的輸出如下。
The count is 3
使用 counter() 方法
這是另一種統計列表中元素出現次數的方法。counter 方法提供了一個字典,其中包含所有元素出現的次數作為鍵值對,其中鍵是元素,值是它出現的次數。我們需要從 collections 中匯入 Counter 模組。
示例
在此示例中,我們使用 counter() 方法統計列表中某個元素的出現次數。
from collections import Counter l = [1,2,7,5,9,1,4,8,10,1] x = 1 d = Counter(l) print('{} has occurred {} times'.format(x, d[x]))
輸出
以上程式碼的輸出如下。
1 has occurred 3 times
廣告