在Python中,计数可以通过多种方法实现,以下是几种常见的方法:
1. 使用`dict`进行计数:
test_lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']counter_dict = {}for item in test_lst:counter_dict[item] = counter_dict.get(item, 0) + 1print(counter_dict)
2. 使用`dict.setdefault`方法进行计数:
test_lst = ['a', 'b', 'c', 'd', 'eshi', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']counter_dict = {}for item in test_lst:counter_dict.setdefault(item, 0)counter_dict[item] += 1print(counter_dict)
3. 使用`collections.Counter`类进行计数:
from collections import Countertest_lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']counter = Counter(test_lst)print(counter)

4. 使用`str.count`方法进行计数:
my_string = "hello world"count = my_string.count('l')print(count)
5. 使用`list.count`方法进行计数:
my_list = [1, 2, 3, 2, 1, 2, 3, 4]count = my_list.count(2)print(count)
6. 使用`tuple.count`方法进行计数:
my_tuple = (1, 2, 3, 2, 4, 2)count_2 = my_tuple.count(2)print("元组中2的个数为:", count_2)
