[转载] Python里面numpy库中zeros()的一些问题

参考链接: Python中的numpy.zeros

Python里面numpy库中zeros函数的一些问题

 定义

本文记录了在使用numpy库中的zeros函数时遇到的一些问题 

定义 

用法:zeros(shape, dtype=float, order=‘C’) 

返回:返回来一个给定形状和类型的用0填充的数组; 

实例: 直接看代码 

np.zeros(5) 

array([0., 0., 0., 0., 0.]) 

np.zeros(5).ndim

1

np.zeros(5).shape

(5,)

*****************************************

np.zeros((5,))

array([0., 0., 0., 0., 0.])

np.zeros((5,)).ndim

1

np.zeros((5,)).shape

(5,)

*****************************************

np.zeros((5,5))

array([[0., 0., 0., 0., 0.],

       [0., 0., 0., 0., 0.],

       [0., 0., 0., 0., 0.],

       [0., 0., 0., 0., 0.],

       [0., 0., 0., 0., 0.]])

np.zeros((5,5)).ndim

2

np.zeros((5,5)).shape

(5, 5)

   

zeros()中shape定义返回数组的形状,np.zeros(5)表示生成一个5个元素全为0的数组,形状为(5,)此时可以理解为控制shape的参数的类型为list,np.zeros((5,))表示生成一个5个元素全为0的数组,形状为(5,)此时可以理解为控制shape的参数的类型为tuple ,np.zeros((5,5))表示生成一个5 * 5 =25个元素全为0的数组,形状为(5,5)此时可以理解为控制shape的参数的类型为矩阵。 注意:python定义元组(tuple)时,如果只含一个元素,要在后面加逗号。 为什么经常在程序里面看到用tuple而不是list:因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。

猜你喜欢

转载自blog.csdn.net/u013946150/article/details/112976696