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

如何让Python的Counter输出仅打印字典内容而不带Counter前缀

解决方法

Counter 是Python内置字典的子类,只需将Counter对象转为普通字典后打印即可得到目标格式。
另外注意你原代码存在变量名拼写错误:你定义的列表变量为colors,调用Counter时误写为了colours,会触发命名报错,修正后的完整代码如下:

from collections import Counter

colors = ['green', 'blue', 'green', 'white', 'white']
colorTotals = Counter(colors)

print(dict(colorTotals))

运行后输出结果为:
{'green': 2, 'white': 2, 'blue': 1}

如果后续不需要使用Counter的专属方法,也可以在统计时直接转成字典存储:

colorTotals = dict(Counter(colors))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:27:01