在Python中如何打印列表元素及其在列表内的出现次数?
Python 部门编码统计实现方案
实现效果
用户依次输入部门编码8、8、10后,会输出如下结果:
部门编码: 8 出现次数: 2
部门编码: 10 出现次数: 1
实现代码
方案1:使用标准库Counter实现(推荐)
from collections import Counter # 收集用户输入的部门编码 dept_code_list = [] while True: input_content = input("请输入部门编码,直接按回车键即可结束输入:").strip() if not input_content: break # 若不需要校验数字格式可删除try-except块,直接存字符串 try: dept_code = int(input_content) dept_code_list.append(dept_code) except ValueError: print("请输入有效的数字格式部门编码") # 统计各编码出现次数 code_counter = Counter(dept_code_list) # 格式化输出结果 for code, count in code_counter.items(): print(f"部门编码: {code} 出现次数: {count}")
方案2:纯字典手动统计(无需导入额外依赖)
# 收集用户输入的部门编码 dept_code_list = [] while True: input_content = input("请输入部门编码,直接按回车键即可结束输入:").strip() if not input_content: break try: dept_code = int(input_content) dept_code_list.append(dept_code) except ValueError: print("请输入有效的数字格式部门编码") # 手动统计次数 code_count = {} for code in dept_code_list: code_count[code] = code_count.get(code, 0) + 1 # 格式化输出结果 for code, count in code_count.items(): print(f"部门编码: {code} 出现次数: {count}")
说明
- 两种方案运行效果完全一致,
Counter是Python标准库内置的统计工具,代码更简洁易读 - 若不需要校验输入为数字,可直接删除
try-except块,将输入内容直接存入列表即可
内容的提问来源于stack exchange,提问作者Evan Schneider
相关产品推荐
相关产品推荐

