np.zeros(shape) 注意shape的规范格式为元组,不是list

既然,官方文档已经明确指出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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值