1. 使用`isdigit()`方法结合循环遍历字符串:
def count_digits(s):count = 0for char in s:if char.isdigit():count += 1return counts = "abc123xyz456"print(count_digits(s)) 输出:6
2. 使用`count()`方法统计列表中数字的个数:
my_list = [1, 2, 3, 1, 4, 1, 5]count = my_list.count(1)print(count) 输出:3
3. 使用`Counter`类统计列表中数字的个数:

from collections import Countermy_list = [1, 2, 3, 1, 4, 1, 5]counter = Counter(my_list)print(counter) 输出:3
4. 使用`dict`或`defaultdict`统计数字出现的个数:
def count_numbers(numbers):count_dict = {}for num in numbers:if num in count_dict:count_dict[num] += 1else:count_dict[num] = 1return count_dictnumbers = [1, 2, 3, 4, 1, 2, 3, 4, 5]result = count_numbers(numbers)print(result) 输出:{1: 2, 2: 2, 3: 2, 4: 2, 5: 1}
5. 使用`count()`方法统计元组中元素的个数:
my_tuple = (1, 2, 3, 2, 4, 2)count_2 = my_tuple.count(2)print("元组中2的个数为:", count_2) 输出:元组中2的个数为: 3
以上方法均可根据不同的数据类型和场景选择使用
