【问题标题】:Dtype work in FROM but not IMPORTDtype 在 FROM 中工作,但不在 IMPORT 中
【发布时间】:2012-10-10 09:54:17
【问题描述】:

我发誓在问这个问题之前,我几乎阅读了所有“FROM vs IMPORT”问题。

在浏览我正在使用的 NumPy 教程时:

import numpy as np

但在声明矩阵的 dtype 时遇到了麻烦:

a = np.ones((2,3),dtype=int32)

我不断收到“NameError: name 'int32' is not defined。”我正在使用 Python v3.2,并且正在遵循随附的暂定教程。我用过:

from numpy import *
a = ones((2,3),dtype=int32)

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

【问题讨论】:

    标签: numpy python-3.x scipy


    【解决方案1】:
    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 中的字符串来定义类型

    【讨论】:

    • 谢谢你,效果很好,想法也少了些阴霾!
    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2011-05-18
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多