我想知道np.size('')返回的事实背后是否有一个基本原理,例如,1鉴于len('')ornp.size([])两者都返回0。
np.sizeof anystr是 1。对于大多数不是列表的 Python 对象也是如此。
调用help它打印:
Help on function size in module numpy:
size(a, axis=None)
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
element_count : int
Number of elements along the specified axis.
...
Run Code Online (Sandbox Code Playgroud)
由此我们看到提供的第一个参数应该是“array_like”,因此str无论如何都不应该是 a 。
正文的源代码np.size是:
if axis is None:
try:
return a.size
except AttributeError:
return asarray(a).size
else:
try:
return a.shape[axis]
except AttributeError:
return asarray(a).shape[axis]
Run Code Online (Sandbox Code Playgroud)
当提供 a 时str,它会调用asarray该对象。这将导致创建一个 0 维数组,其大小始终为 1。
>>> a = np.asarray('')
>>> a
array('', dtype='<U1')
>>> a.size
1
>>> a.ndim
0
>>>
>>> b = np.asarray('example str')
>>> b
array('example str', dtype='<U11')
>>> b.size
1
>>> b.ndim
0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |