NameError:未定义全局名称“ operator” [英] NameError: global name 'operator' is not defined
问题描述
import KNN
def c(i,d,l,k):
dss=d.shape[0]
dm=tile(i,(dss,1))-d
sqm=dm**2
sqd=sqm.sum(axis=1)
dist=sqd**0.5
sDI=dist.argsort()
clc={}
for i in range(k):
vl=l[sDI[i]]
clc[vl]=clc.get(vl,0)+1
sCC=sorted(clc.items(),key=operator.itemgetter(1),reverse=True)
return sCC[0][0]
c([0,0],g,l,3)
错误:
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
c([0,0],g,l,3)
File "<pyshell#31>", line 12, in c
sCC=sorted(clc.items(),key=operator.itemgetter(1),reverse=True)
NameError: global name 'operator' is not defined
KNN包含以下代码:
KNN contains the following code:
from numpy import *
import operator
def createDataSet():
group = array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
labels = ['A','A','B','B']
return group, labels
为什么会出现上述错误?程序在Python 3.3.2上运行。这段代码是在Python中运行的简单的k分类算法。
Why is there a error as mentioned above? Program is run on Python 3.3.2. This code is a simple k-classification algorithm run in Python.
推荐答案
您需要 import运算符
到本地名称空间; import KNN
也不会导入它导入的子模块。
You need to import operator
into the local namespace; import KNN
will not also import the submodules it imports.
通常,您需要明确说明任何以及您使用的所有模块和对象,但 builtins
( https://docs.python.org/2/library/functions.html )。
As a rule, you need to be explicit about any and all modules and objects you use, with the exception of the builtins
(https://docs.python.org/2/library/functions.html).
与某些其他语言不同,没有隐式导入。
Unlike some other languages, there are no implicit imports.
有关导入的高级技巧/教程:
您可能会想使用 KNN.operator
。它在这里可用,因为它是由 KNN
导入的。但是,这几乎总是令人遗憾的决定,因为这使情况感到困惑:这是一个特殊的模块吗?如果是这样,它的界面是什么?保存可爱性,要明确。
Advanced tip/editorial on imports:
You might be tempted to use KNN.operator
. It's available there because it was imported by KNN
. However, this is almost always a regrettable decision, as confuses the picture: Is this a special module? If so what's its interface? Save the cuteness, be explicit.
这篇关于NameError:未定义全局名称“ operator”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!