You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:18:05