正如在评论中指出,Python的类型,如int
,float
,str
,list
等都是可赎回,即可以使用int()
并获得0
,或str()
和list()
,并得到一个空字符串或列表。
>>> type(42)()
0
同样也适用于numpy
类型。你可以使用dtype
属性numpy的阵列的类型,然后用它来初始化“失踪”的价值观:
>>> A = np.array([1, 2, 3, 4, float("nan")]) # common type is float64
>>> A
array([ 1., 2., 3., 4., nan])
>>> A[np.isnan(A)] = A.dtype.type() # nan is replaced with 0.0
>>> A
array([ 1., 2., 3., 4., 0.])
>>> B = np.array([1, 2, 3, -1, 5]) # common type is int64
>>> B
array([ 1, 2, 3, -1, 5])
>>> B[B == -1] = B.dtype.type() # -1 is replaced with
>>> B
array([1, 2, 3, 0, 5])
这也适用于但是提供一个无参数的构造函数,其他类,其结果将是一流的,而不是null
在你的榜样的实例..
>>> class Foo(object): pass
>>> type(Foo())()
<__main__.Foo at 0x7f8b124c00d0>
'INT()''返回由0'默认和'浮动()''返回由0.0'默认。这有帮助吗? – gtlambert
@idjaw,并执行'x = something或int()'不满足相同的需求? – Chris