向量元组创建
代码块1(创建)
a = np.zeros(4); print(f"np.zeros(4) : a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
a = np.zeros((4,)); print(f"np.zeros(4,) : a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
a = np.random.random_sample(4); print(f"np.random.random_sample(4): a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
输出:
np.zeros(4) : a = [0. 0. 0. 0.], a shape = (4,), a data type = float64
np.zeros(4,) : a = [0. 0. 0. 0.], a shape = (4,), a data type = float64
np.random.random_sample(4): a = [0.24660509 0.65617874 0.20796114 0.99258047], a shape = (4,), a data type = float64
代码块2
a = np.arange(4.); print(f"np.arange(4.): a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
a = np.random.rand(4); print(f"np.random.rand(4): a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
输出:
np.arange(4.): a = [0. 1. 2. 3.], a shape = (4,), a data type = float64
np.random.rand(4): a = [0.94521094 0.35495575 0.85364377 0.14953348], a shape = (4,), a data type = float64
np.arange()
函数返回一个有终点和起点的固定步长的排列,如[1,2,3,4,5],起点是1,终点是6,步长为1。
参数个数情况: np.arange()函数分为一个参数,两个参数,三个参数三种情况
1)一个参数时,参数值为终点,起点取默认值0,步长取默认值1。
2)两个参数时,第一个参数为起点,第二个参数为终点,步长取默认值1。
3)三个参数时,第一个参数为起点,第二个参数为终点,第三个参数为步长。其中步长支持小数
代码块3
# NumPy routines which allocate memory and fill with user specified values
a = np.array([5,4,3,2]); print(f"np.array([5,4,3,2]): a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
a = np.array([5.,4,3,2]); print(f"np.array([5.,4,3,2]): a = {
a}, a shape = {
a.shape}, a data type = {
a.dtype}")
输出:
np.array([5,4,3,2]): a = [5 4 3 2], a shape = (4,), a data type = int32
np.array([5.,4,3,2]): a = [5. 4. 3. 2.], a shape = (4,), a data type = float64
也可以自己指定数据类型,为元组的第一个
#vector indexing operations on 1-D vectors
a = np.arange(10)
print(a)
#访问元素
print(f"a[2].shape: {
a[2].shape} a[2] = {
a[2]}