我发誓,在问这个问题之前,我几乎阅读了所有“FROM vs IMPORT”的问题。
在浏览我使用的NumPy教程时:
import numpy as np
但在声明类似矩阵的dtype时遇到了麻烦:
a = np.ones((2,3),dtype=int32)
我一直得到“NameError:name'int32'未定义。”我正在使用Python v3.2,并且正在遵循随之而来的试验性教程。我用过:
from numpy import *
a = ones((2,3),dtype=int32)
哪个有效。任何关于为什么会这样做的见解将非常感激。 提前谢谢!
答案 0 :(得分:4)
import numpy as np
#this will work because int32 is defined inside the numpy module
a = np.ones((2,3), dtype=np.int32)
#this also works
b = np.ones((2,3), dtype = 'int32')
#python doesn't know what int32 is because you loaded numpy as np
c = np.ones((2,3), dtype=int32)
回到你的例子:
from numpy import *
#this will now work because python knows what int32 is because it is loaded with numpy.
d = np.ones((2,3), dtype=int32)
我倾向于使用字符串定义类型,如数组b