1. 使用内置函数 `len()`:
my_list = [1, 2, 3, 4, 5]
count = len(my_list)
print(count) 输出:5
2. 使用列表的 `count()` 方法统计特定元素出现的次数:
my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
count_2 = my_list.count(2)
count_4 = my_list.count(4)
print(count_2) 输出:2
print(count_4) 输出:4
3. 使用 `collections.Counter` 类进行元素统计:
from collections import Counter
my_list = ['a', 'c', 'b', 'c', 'a', 'a']
count_dict = Counter(my_list)
print(count_dict) 输出:{'a': 3, 'c': 2, 'b': 1}
以上方法都可以用来计算列表中元素的个数