📅  最后修改于: 2023-12-03 15:37:27.461000             🧑  作者: Mango
在 Python 中有许多方法用于计数。在本文中,我们将介绍一些常用的方法来计数并说明它们的用途。
len()
函数可以方便地计算对象中元素的数量,如字符串、列表、元组等。
str = "Hello World"
print(len(str)) # 输出:11
lst = [1, 2, 3, 4, 5]
print(len(lst)) # 输出:5
tpl = (1, 2, 3, 4, 5)
print(len(tpl)) # 输出:5
count()
方法适用于字符串、列表和元组。它可以计算指定元素在对象中出现的次数。
str = "Hello World"
print(str.count("l")) # 输出:3
lst = [1, 2, 3, 4, 5, 3, 3]
print(lst.count(3)) # 输出:3
tpl = (1, 2, 3, 4, 5, 3, 3)
print(tpl.count(3)) # 输出:3
collections
模块提供了一个名为 Counter
的类,它可以用于计数元素在列表中出现的次数。
from collections import Counter
lst = [1, 2, 3, 4, 5, 3, 3]
counter = Counter(lst)
print(counter[3]) # 输出:3
defaultdict
类提供了一个更方便的方式来计数元素在列表中出现的次数。在创建一个 defaultdict
对象时,可以将它的默认工厂函数设置为 int
,这样当对象中没有元素时,会自动初始化为 0。
from collections import defaultdict
lst = [1, 2, 3, 4, 5, 3, 3]
counter = defaultdict(int)
for num in lst:
counter[num] += 1
print(counter[3]) # 输出:3
在 Python 中我们可以通过以上方法进行计数操作。len()
函数适用于字符串、列表、元组等对象,可以计算对象中元素的数量。count()
方法适用于字符串、列表和元组,可以统计指定元素在对象中出现的次数。collections
模块提供了一个 Counter
类,可以用于计数元素在列表中出现的次数。defaultdict
类也可以用于计数,它提供了更方便的方式来统计元素在列表中出现的次数。