計算 Python 中列表中元素出現的次數
在本文中,我們給定了一個列表和一個字串。我們需要找出所給字串在列表中作為元素出現的次數。
使用計數器
collections 模組中的 counter 函式將為我們提供列表中每個元素的計數。從計數結果中,我們只能提取該帳戶公平地匹配我們正在搜尋的元素的索引。
示例
from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
elem = 'Mon'
# Given list and element
print("Given list:\n", Alist)
print("Given element:\n",elem)
cnt = Counter(Alist)
print("Number of times the element is present in list:\n",cnt[elem])輸出
執行以上程式碼,將得到以下結果 −
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2
使用計數
count 函式將給定的流作為引數,並在給定的列表中搜索該流。
示例
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
elem = 'Mon'
# Given list and element
print("Given list:\n", Alist)
print("Given element:\n",elem)
cnt = Alist.count('Mon')
print("Number of times the element is present in list:\n",cnt)輸出
執行以上程式碼,將得到以下結果 −
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP