python 按位置关系输出矩阵元素
描述:依次输出矩阵中最近邻的元素
例如:输入:
[[1, 2, 3]
[4, 5, 6]
[7, 8, 9]]
输出:
[[ 1. 2. 4. 5. 3. 6. 7. 8. 9.]
[ 2. 1. 3. 4. 5. 6. 7. 8. 9.]
[ 3. 2. 5. 6. 1. 4. 7. 8. 9.]
[ 4. 1. 2. 5. 7. 8. 3. 6. 9.]
[ 5. 1. 2. 3. 4. 6. 7. 8. 9.]
思想:采用坐标进行判断,距离中心点一跳的元素坐标与中心点的坐标的平方差小于2,依次类推
import numpy as np #zhaodaozaizhidingfanweineideshuzi a=np.array([[1,2,3],[4,5,6],[7,8,9]]) b=a[0][0] c,d=a.shape e=np.zeros(shape=[c*d,c*d]) # print (d) k=0 def sround1(distance,m,n,wend,hend): e[m*3+n][0]=a[m][n] k=1 for d in range(distance): for i in range(wend): for j in range(hend): if np.square(i-m)+np.square(j-n)<=2*np.square(d) and np.square(i-m)+np.square(j-n)>2*np.square(d-1): e[m*3+n][k]=a[i][j] k=k+1 print (e) def start(c, d): d=max(c,d) for i in range(c): for j in range(d): sround1(d,i,j,c,d) print (e) if __name__=='__main__': start(3,3)
[ 6. 2. 3. 5. 8. 9. 1. 4. 7.]
[ 7. 4. 5. 8. 1. 2. 3. 6. 9.]
[ 8. 4. 5. 6. 7. 9. 1. 2. 3.]
[ 9. 5. 6. 8. 1. 2. 3. 4. 7.]]