Python3下机器学习实战KNN代码出现AttributeError: ‘dict’ object has no attribute错误
来源:互联网 发布:mac os 硬件要求 编辑:程序博客网 时间:2024/06/08 12:48
出现错误的代码时:
result = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
错误显示:
AttributeError: 'dict' object has no attribute 'iteritems'
之所以会出现上述错误是因为python3中已经没有这个属性,直接改为items即可:
result = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)
知识点补充:
operator.itemgetter函数
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子。
a = [1,2,3] b=operator.itemgetter(1) //定义函数b,获取对象的第1个域的值print(b(a))
输出:
2
b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个域的值print(b(a))
输出:
(2, 1)
要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值。
字典items()操作方法:
x = {'title':'python web site','url':'www.iplaypy.com'}print(x.items())
输出:
[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]
从结果中可以看到,items()方法是将字典中的每个项分别做为元组,添加到一个列表中,形成了一个新的列表容器。如果有需要也可以将返回的结果赋值给新变量,这个新的变量就会是一个列表数据类型。
a=x.items()print(a)
输出:
[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]
print(type(a))
输出:
<\type ‘list’>
参考资料:Python 字典items返回列表
阅读全文
1 0
- Python3下机器学习实战KNN代码出现AttributeError: ‘dict’ object has no attribute错误
- python机器学习实战3.2提示错误AttributeError: type object 'str' has no attribute '_name_'
- Python3下AttributeError: 'dict' object has no attribute 'iteritems'的问题分析
- Python3下AttributeError: 'dict' object has no attribute 'iteritems'的问题分析
- AttributeError: 'dict' object has no attribute 'iteritems'
- AttributeError: 'dict' object has no attribute 'iteritems'
- AttributeError: 'dict' object has no attribute 'has_key'
- AttributeError: 'dict' object has no attribute 'interitems'
- AttributeError: 'dict' object has no attribute 'iteritems'
- Python2.X与Python3.X编程代码笔记(1):AttributeError: 'dict' object has no attribute 'iteritems'
- Python3.6 下yield的常见错误(AttributeError: 'generator' object has no attribute 'next')
- 出现错误如下:AttributeError: 'module' object has no attribute 'SSL_ST_INIT'
- python3 报错: AttributeError: 'module' object has no attribute 'urlopen'
- 关于python3.2的'dict' object has no attribute 'iteritems'
- web.py 启动时候出现AttributeError: 'module' object has no attribute 'inet_pton'错误
- web.py 启动时候出现AttributeError: 'module' object has no attribute 'inet_pton'错误
- 使用Buildozer部署时,出现AttributeError: 'NoneType' object has no attribute 'group'错误的解决
- Ubuntu16.04上启动Spyder出现错误AttributeError: 'module' object has no attribute '_base'
- 结构体中最后一个成员为[0]或[1]长度数组(柔性数组成员)的用法
- 机房收费系统--小细节
- 算法运行时间n3,n2, n, nlogn对比
- linus下安装MyCat
- 【JavaScript 】输出
- Python3下机器学习实战KNN代码出现AttributeError: ‘dict’ object has no attribute错误
- 实验吧-忘记密码了?writeup
- 周中训练笔记19——树形DP总结
- Mybatis的动态sql-----注解
- 逆解最大公约数与最小公倍数
- 第三章:操作符
- 深入浅出SQL触发器
- 假如时光倒流,我会这么学习Java
- Softmax分类器