Python调用Counter时报TypeError:'module'对象不可调用的原因及解决办法
错误原因
你的导入语句存在逻辑错误:collections是Python内置的容器数据类型模块,Counter是该模块下提供的可调用类。你当前写的import collections as Counter是将整个collections模块重命名为了Counter,后续执行Counter(dataset['Best'])时,本质是尝试把模块对象当函数/类调用,因此抛出TypeError: 'module' object is not callable错误。
修复方案
可以任选以下一种方案修改:
- 方案一(推荐):从collections模块单独导入Counter类,原有调用逻辑无需修改
把导入语句改为:from collections import Counter - 方案二:保留导入整个collections模块的写法,同步修改导入和调用代码
导入语句改为:
对应的执行代码改为:import collectionsprint(sorted(collections.Counter(dataset['Best']).items()))
内容的提问来源于stack exchange,提问作者Numan Ahmad
相关产品推荐
相关产品推荐

