既然,官方文档已经明确指出shape为整数的元组,那我们平时在使用的时候也就用元组,不要去用list以避免造成不必要的错误。
一开始没有注意到shape是元组类型,于是产生了一个疑问。
shape到底是一个元组呀还是一个数组(列表)?
于是,我就试了试一下两种代码:
b = np.ones((3,6))
b = np.ones([3,6])
发现两者都能创建成功,而且编译器也没报错,然后我的疑问就更大了,就去看这俩函数的底层,如下:
@set_module('numpy')
def ones(shape, dtype=None, order='C'):
"""
Return a new array of given shape and type, filled with ones.
Parameters
----------
shape : int or sequence of ints
Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
The desired data-type for the array, e.g., `numpy.int8`. Default is
`numpy.float64`.
order : {'C', 'F'}, optional, default: C
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
Returns
-------
out : ndarray
Array of ones with the given shape, dtype, and order.
发现,底层解释中shape为:
int or sequence of ints
Shape of the new array, e.g., (2, 3) or 2.
意思是: int或int的序列
新数组的形状,例如,(2, 3)或2 。
因此,我理解是——
其中,序列的含义为:列表、元组、数组或其他序列类型。所以,shape只要是个int的序列就行了。
但是,我在网上查了大部分的教程发现在介绍shape时都是直接说shape是一个元组,至于原因也没说,就去查了一下官方文档如下:
对于shape函数,官方文档是这么说明:
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension.
意思是:数组的维度。这是一个整数的元组,元组中的每一个元素对应着每一维度的大小(size)。
既然,官方文档已经明确指出shape为整数的元组,那我们平时在使用的时候也就用元组,不要去用list以避免造成不必要的错误。
https://blog.csdn.net/henu1710252658/article/details/98509533