Skip to main content
 首页 » 编程设计

python之如何在 numpy 中使用 ones() 获取数字数组

2025年05月04日21jillzhang

您好,我在 Matlab 中有一段代码生成以下序列。

[ones(1,6*2) 2 ones(1,6*2-1) 2 ones(1,6*2) 1] 
 
ans = 
 
  Columns 1 through 18 
     1    1    1    1    1    1    1    1    1    1    1    1    2    1    1    1    1    1 
 
  Columns 19 through 36 
     1    1    1    1    1    1    2    1    1    1    1    1    1    1    1    1    1    1 
 
  Columns 37 through 38 
     1    1 

我想在 Python 中生成类似的数字数组。

我尝试生成如下。

ConvStride = [np.ones((12,),dtype=int),2,np.ones((11,),dtype=int),2,np.ones((12,),dtype=int),1] 
 
Ans= [1 1 1 1 1... 1],2,[1 1 1 ... 1],2,[1 1 1 1....1],1 
 
ConvStride = [np.ones((12,),dtype=int),2,np.ones((11,),dtype=int),2,np.ones((12,),dtype=int),1] 

需要

[ 1 1 1 .....1 2 1 1 1 .....1 2 111 ....1 1]

你能告诉我这里的工作吗。

请您参考如下方法:

使用np.r_:

np.r_[np.ones(12,int),2,np.ones(11,int),2,np.ones(12,int)] 
# array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
#        1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])