1.使用循环
nums = [1, 1, 1, 2, 2, 3]
# 构建一个空字典来存储元素和它们出现的次数
count_dict = {}
# 遍历列表,更新字典中每个元素出现的次数
for num in nums:
if num in count_dict:
count_dict[num] += 1
else:
count_dict[num] = 1
# 输出统计结果
for num, count in count_dict.items():
print(f"元素 {num} 出现了 {count} 次。")
元素 1 出现了 3 次。
元素 2 出现了 2 次。
元素 3 出现了 1 次。
2.使用collections库
from collections import Counter
nums = [1, 1, 1, 2, 2, 3]
# 使用Counter统计列表中每个元素的出现次数
counts = Counter(nums)
# 输出统计结果
for num, count in counts.items():
print(f"元素 {num} 出现了 {count} 次。")
元素 1 出现了 3 次。
元素 2 出现了 2 次。
元素 3 出现了 1 次。