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

Python实现库存功能时如何统计列表同类元素避免重复打印

问题根因

当前循环直接遍历原始库存列表,列表内重复存储的物品会多次进入循环逻辑,导致同个物品重复打印;另外每次循环都调用.count()会重复遍历整个列表做统计,库存条目多的时候会有不必要的性能损耗。

修正方案

你已经导入了collections.Counter,这个工具本身就是用来做可迭代对象元素计数的,直接遍历它统计后的键值对输出即可,一次统计就能拿到所有物品的去重结果和对应数量:

from collections import Counter

class Player:
    def __init__(self):
        self.inventory = ["wood","wood","flint","steel"]

    def print_inv(self):
        print(" -- Inventory -- ")
        item_count_map = Counter(self.inventory)
        for item_name, total in item_count_map.items():
            print(f" > {item_name}({total})")

Player().print_inv()

执行后输出完全匹配要求的格式:

-- Inventory -- 
 > wood(2)
 > flint(1)
 > steel(1)

如果不想依赖Counter,也可以先把库存列表转成集合自动去重,再遍历统计每个物品的数量:

class Player:
    def __init__(self):
        self.inventory = ["wood","wood","flint","steel"]

    def print_inv(self):
        print(" -- Inventory -- ")
        for item_name in set(self.inventory):
            print(f" > {item_name}({self.inventory.count(item_name)})")

Player().print_inv()

提示:第二种方案因为循环内还是会反复调用.count()遍历全列表,只适合库存规模小的场景使用,库存条目多的时候优先选Counter的方案,性能更好。

内容的提问来源于stack exchange,提问作者bigboibob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:21:21