2017-10-08 50 views
2

返回一個新的向量,其中每個元素由4個連續的零分隔。試圖實現[4,2,1] - > [4,0,0,0,0,2,0,0,0,0,1]高效地插入數字 - NumPy/Python

def zero_insert(x): 
    y = np.zeros((5*(len(x)-1))+1, dtype=np.int) 
    for i in range(len(x)): 
     y[5*i] = x[i] 
    return y 

回答

3

初始化和分配 -

x = np.asarray(x) # convert to array 
n = 4    # number of zeros to be inserted 
N = n+1 
out = np.zeros((len(x)-1)*N+1,dtype=x.dtype) 
out[::N] = x 
+1

我收到錯誤「AttributeError:'list'object has no attribute'dtype'」 –

+0

@NickDuddy需要一個數組作爲輸入。請檢查編輯。 – Divakar

+0

@NickDuddy那麼,發佈的解決方案是否適合你? – Divakar