一、广播
import numpy as np a=np.array([1,3,5,7]) b=np.array([2,4,6,8]) print(a+b) print(a-b) print(a*b)#不是矩阵乘法而是两两相成 print(a/b) a=np.array([[1,3,5,7],[2,4,6,8]]) c=np.array([10,20,30,40])#宽度相同就可以进行运算,多的数运算少的数 print(a+c)
二、迭代器遍历等
import numpy as np #1.迭代器遍历 a=np.arange(12) a=a.reshape(3,4) for x in np.nditer(a,order="F"):#遍历元素,与矩阵shape无关 print(x) print(a.T," --------------------")#矩阵转置 #2.copy+C、F风格遍历 b=np.arange(12) b=b.reshape(2,6) c=b.copy(order="C")#C风格,从左往右,从上往下遍历 for x in np.nditer(c): print(x) d=b.copy(order="F")#F风格,从上往下,从左往右遍历 for x in np.nditer(d): print(x) #3.权限改为可写入 e=np.arange(12) e=e.reshape(2,6) for x in np.nditer(e): x=10 print(x)#这种形式不会改变原来的数组 for x in np.nditer(e,op_flags=["readwrite"]):#权限改为可写入 x[...]=2*x print(e) #4.flags f=np.arange(12) f=f.reshape(2,6) for x in np.nditer(a,flags=['external_loop']):#把元素当成一维数组打印 print(x) for x in np.nditer(a,flags=['c_index']): print(x)#C风格打印 for x in np.nditer(a, flags=['f_index']): print(x) #F风格打印 #5.可广播的,前提列数相同 i=np.arange([0,2,4,6,8,10],[12,14,16,18,20,22]) j=np.arange([1,1,1,1,1,1]) for x,y in np.nditer([a,b]): print(x,y)