本文目录导读:

我来介绍几种Python列表元素统计的方法,包含常见案例:
基础计数方法
使用 count() 方法
# 统计单个元素出现次数
numbers = [1, 2, 3, 2, 4, 2, 5]
count_2 = numbers.count(2)
print(f"数字2出现 {count_2} 次") # 输出: 数字2出现 3 次
# 统计字符串列表
fruits = ['apple', 'banana', 'apple', 'orange', 'apple']
count_apple = fruits.count('apple')
print(f"apple出现 {count_apple} 次") # 输出: apple出现 3 次
统计所有元素出现次数
使用 collections.Counter
from collections import Counter
# 基本用法
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(numbers)
print(counter) # 输出: Counter({4: 4, 3: 3, 2: 2, 1: 1})
# 获取最常见的元素
print(counter.most_common(2)) # 输出: [(4, 4), (3, 3)]
# 获取特定元素出现次数
print(counter[3]) # 输出: 3
使用字典手动统计
def count_elements(lst):
count_dict = {}
for item in lst:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
return count_dict
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
result = count_elements(numbers)
print(result) # 输出: {1: 1, 2: 2, 3: 3, 4: 4}
实用统计案例
案例1:学生成绩统计分析
scores = [85, 92, 78, 85, 90, 85, 88, 92, 76, 85]
# 统计分数分布
from collections import Counter
score_counter = Counter(scores)
print("分数分布:")
for score, count in sorted(score_counter.items()):
print(f"{score}分: {count}人")
# 统计各分数段
levels = {'优秀(90+)': 0, '良好(80-89)': 0, '及格(60-79)': 0}
for score in scores:
if score >= 90:
levels['优秀(90+)'] += 1
elif score >= 80:
levels['良好(80-89)'] += 1
else:
levels['及格(60-79)'] += 1
print("\n分数段统计:")
for level, count in levels.items():
print(f"{level}: {count}人")
案例2:文本分析
text = "hello world hello python hello programming"
words = text.split()
# 统计单词出现次数
word_counter = Counter(words)
print("单词统计:")
for word, count in word_counter.most_common():
print(f"'{word}': {count}次")
# 找出出现最多的单词
most_common_word, times = word_counter.most_common(1)[0]
print(f"\n出现最多的单词: '{most_common_word}', 出现{times}次")
案例3:数据质量检查
data = [1, 2, None, 3, 1, None, 2, 4, 5, None]
# 统计缺失值
missing_count = data.count(None)
print(f"缺失值数量: {missing_count}")
# 统计完整数据
valid_data = [x for x in data if x is not None]
print(f"有效数据数量: {len(valid_data)}")
# 统计非空数据分布
from collections import Counter
valid_counter = Counter(valid_data)
print("有效数据分布:", valid_counter)
案例4:多维列表统计
# 统计二维列表中所有数字的出现次数
matrix = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
flattened = [num for row in matrix for num in row]
counter = Counter(flattened)
print("所有数字出现次数:")
for num, count in sorted(counter.items()):
print(f"{num}: {count}次")
条件统计
按条件筛选统计
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 统计偶数数量
even_count = sum(1 for num in numbers if num % 2 == 0)
print(f"偶数个数: {even_count}") # 输出: 5
# 统计大于5的数字数量
above_5_count = sum(1 for num in numbers if num > 5)
print(f"大于5的数字个数: {above_5_count}") # 输出: 5
性能对比
import time
from collections import Counter
# 创建大列表
big_list = [i % 100 for i in range(100000)]
# 方法1:使用Counter
start = time.time()
result1 = Counter(big_list)
print(f"Counter方法耗时: {time.time() - start:.4f}秒")
# 方法2:使用字典
start = time.time()
result2 = {}
for item in big_list:
result2[item] = result2.get(item, 0) + 1
print(f"字典方法耗时: {time.time() - start:.4f}秒")
对于简单的单个元素计数,使用 count() 方法;对于统计所有元素出现次数,推荐使用 Counter,它既高效又功能丰富;对于大数据集,可以考虑使用 pandas 库的 value_counts() 方法。