如何在 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
廣告