溫馨提示×

Python中怎么統(tǒng)計特定元素的個數(shù)

小億
192
2024-04-23 15:58:44
欄目: 編程語言

在Python中,可以使用count()方法來統(tǒng)計特定元素在列表中的個數(shù)。例如:

my_list = [1, 2, 3, 1, 4, 1, 5]
count = my_list.count(1)
print(count)  # 輸出:3

如果要統(tǒng)計特定元素在字符串中的個數(shù),可以使用count()方法。例如:

my_string = "hello world"
count = my_string.count('l')
print(count)  # 輸出:3

另外,還可以使用collections模塊中的Counter類來統(tǒng)計元素的個數(shù)。例如:

from collections import Counter

my_list = [1, 2, 3, 1, 4, 1, 5]
counter = Counter(my_list)
print(counter[1])  # 輸出:3

0