報錯代碼:
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’)]