Dtype在FROM中工作但不在IMPORT中工作

时间:2012-10-19 18:14:20

标签: numpy python-3.x scipy

我发誓,在问这个问题之前,我几乎阅读了所有“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)

哪个有效。任何关于为什么会这样做的见解将非常感激。 提前谢谢!

1 个答案:

答案 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