Python3下机器学习实战KNN代码出现AttributeError: ‘dict’ object has no attribute错误

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_35512245/article/details/78639317

出现错误的代码时:

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返回列表

猜你喜欢

转载自blog.csdn.net/sinat_35512245/article/details/78639317
今日推荐