機器學習實戰:KNN代碼報錯“AttributeError: 'dict' object has no attribute 'iteritems'”


 

報錯代碼:

 sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True) 

解決辦法:

Python3中不再支持iteritems(),將iteritems()改成items()


 

一、 operator.iteritems()函數介紹

 1. 作用:iteritems()函數用於獲取對象某一個域的值。

2. 例一:

1 a = [1,2,3] 
2 b=operator.itemgetter(1)      //定義函數b,獲取對象的第1個域的值
3 print(b(a)) 

輸出:2

  例二:

1 b=operator.itemgetter(1,0)   //定義函數b,獲取對象的第1個域和第0個域的值
2 print(b(a)) 

輸出:(2,1)

 

二、字典items()操作方法

1. 作用:items()方法是將字典中的每個項分別做為元組,添加到一個列表中,形成了一個新的列表容器

2. 例一:

1 x = {'title':'python web site','url':'www.iplaypy.com'}
2 print(x.items())

輸出:[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]

如果有需要也可以將返回的結果賦值給新變量,這個新的變量就會是一個列表數據類型。

1 a=x.items()
2 print(a)

輸出:[(‘url’, ‘www.iplaypy.com’), (‘title’, ‘python web site’)]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM