Python如何统计列表各元素出现次数,不重复输出元素及对应计数
问题解答
代码错误原因
你当前代码没有输出是两个核心错误导致的:
- 打印语句放在了
continue关键字之后,continue执行后会直接跳过本次循环剩余代码进入下一轮,你写的打印逻辑永远不会被触发 - 遍历
finished_sandwiches列表的同时执行remove操作修改列表本身,会导致遍历索引错位,跳过部分元素;同时全局的temp计数变量没有在统计新品类时重置,计数逻辑完全错误
实现方案
方案1:使用标准库collections.Counter(推荐,代码最简洁)
这是Python专门用来做频次统计的内置工具,完全符合你的需求:
from collections import Counter sandwich_orders = ['chicken','egg','ham','beef','egg','fish','beef','beef'] finished_sandwiches = [] while sandwich_orders: in_between = sandwich_orders.pop() print("I made your " + in_between.title() + " sandwich.") finished_sandwiches.append(in_between) print("The following sandwiches were made: ") count_result = Counter(finished_sandwiches) for sandwich_name, count in count_result.items(): print(f"{sandwich_name.title()}({count})")
方案2:纯基础语法实现(无需导入额外库,适合巩固基础)
如果你还没学到Counter,用基础的字典做统计也可以实现:
sandwich_orders = ['chicken','egg','ham','beef','egg','fish','beef','beef'] finished_sandwiches = [] while sandwich_orders: in_between = sandwich_orders.pop() print("I made your " + in_between.title() + " sandwich.") finished_sandwiches.append(in_between) print("The following sandwiches were made: ") count_dict = {} # 先统计每个品类的数量 for sandwich in finished_sandwiches: if sandwich not in count_dict: count_dict[sandwich] = 0 count_dict[sandwich] += 1 # 统一输出结果 for sandwich_name, count in count_dict.items(): print(sandwich_name.title() + "(" + str(count) + ")")
内容的提问来源于stack exchange,提问作者davecodes_029
相关产品推荐
相关产品推荐

