Python中怎么统计特定元素的个数

565
2024/5/5 15:58:44
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,可以使用count()方法来统计特定元素在列表中的个数。例如:

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

如果要统计特定元素在字符串中的个数,可以使用count()方法。例如:

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

另外,还可以使用collections模块中的Counter类来统计元素的个数。例如:

from collections import Counter

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Python如何向空字典添加内容