嗨,我在Matlab中有一个代码,该代码生成以下序列。
dragstart
我想在Python中生成相似的数字数组。
我试图生成如下。
[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
必填
[1 1 1 ..... 1 2 1 1 1 ..... 1 2 111 .... 1 1]
请让我知道这里的解决方法。
答案 0 :(得分:3)
使用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])
答案 1 :(得分:2)
您可以使用类似的python语法创建列表,然后将其转换为numpy数组
import numpy as np
x = [1]*(6*2) + [2] + [1]*(6*2-1) + [2] + [1]*(6*2) + [1]
ans = np.array(x)
如果要使用numpy进行所有操作,则可以使用hstack
。
np.hstack([np.ones(6*2, int), 2, np.ones(6*2-1, int), 2, np.ones(6*2, int), 1])