如何让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
相关产品推荐
相关产品推荐

