亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python 實(shí)現(xiàn)矩陣填充0的例子

 更新時(shí)間:2019年11月29日 08:38:50   作者:icaoys  
今天小編就為大家分享一篇python 實(shí)現(xiàn)矩陣填充0的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

需求:

原矩陣

[[1 2 3]
 [4 5 6]
 [7 8 9]]

在原矩陣元素之間填充元素 0,得到

[[1. 0. 2. 0. 3.]
 [0. 0. 0. 0. 0.]
 [4. 0. 5. 0. 6.]
 [0. 0. 0. 0. 0.]
 [7. 0. 8. 0. 9.]]

思路:

先求出擴(kuò)充矩陣的維度,再按照每一行每一列遍歷,根據(jù)元素的索引規(guī)律依次賦值,最終實(shí)現(xiàn)新的擴(kuò)充矩陣。這個(gè)思路實(shí)現(xiàn)如下:

import numpy as np

def PadMat(Ndim, Mat):
 Brow = Bcol = 2*Ndim-1
 B = np.zeros([Brow, Bcol])
 for row in range(Brow):
 if row%2 == 0:
 for col in range(Bcol):
 if col%2 == 0:
 pos_c = int(col/2)
 pos_r = int(row/2)
 # print(row, col)
 B[row, col] = Mat[pos_r, pos_c]
 else:
 B[row, col] = 0
 return B


# A = np.arange(9) + 1
# A = A.reshape([3, 3])
A = np.arange(16) + 1
A = A.reshape([4, 4])
# print(A.shape[0])
N = Arow = Acol = A.shape[0]

NewMat = PadMat(Ndim=N, Mat=A)
print(A)
print(NewMat)

總結(jié):

這個(gè)思路很直接,但是循環(huán)套循環(huán)是一個(gè)很笨的辦法,而且遍歷也很慢。不知道網(wǎng)友有什么好的思路嗎?

以上這篇python 實(shí)現(xiàn)矩陣填充0的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論