Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đếm Số Lần Xuất Hiện Phần Tử Trong List (Count Occurrences of an Element in a List) trong Python


Trong bài này ta cho một list và một chuỗi. Ta cần tìm chuỗi cho trước xuất hiện bao nhiêu lần làm phần tử trong list.

Với Counter

Hàm Counter từ module collections cho số lượng mỗi phần tử trong list. Từ kết quả đếm ta trích xuất chỉ count cho phần tử ta đang tìm.

Ví dụ

from collections import Counter Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] elem = 'Mon' # Danh sách và phần tử cho trước 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])

Đầu ra

Chạy mã trên cho kết quả sau:

Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2

Với count

Hàm count nhận chuỗi cho trước làm tham số và tìm chuỗi đó trong list cho trước.

Ví dụ

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] elem = 'Mon' # Danh sách và phần tử cho trước 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)

Đầu ra

Chạy mã trên cho kết quả sau:

Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2