# 如何像在 MATLAB 中一样在 Python 中创建数字范围

##### 问题描述投票：0回答：5

MATLAB：

``a = 1:0.5:10``
``a = [1 1.5 2 2.5 3 3.5 .... 9.5 10]``

python matlab range
##### 5个回答
9

``np.arange``

``np.arange``

``````start = 0
stop = 3
step = 0.5
a = np.arange(start, stop+step, step)
``````

6

Numpy 有

``arange``
``r_``
，看起来像这样：

``````import numpy as np
print(np.arange(1, 3, .5))
# [ 1.   1.5  2.   2.5]
print(np.r_[1:3:.5])
# [ 1.   1.5  2.   2.5]
``````

``linspace``

``arange``

``num``

``step``

``````print(np.linspace(1, 3, num=5))
# [ 1.   1.5  2.   2.5  3. ]
``````

``````print(np.linspace(1, 3, num=4, endpoint=False))
# [ 1.   1.5  2.   2.5]
``````

2

``````import numpy as np
a = np.arange(1, 10, 0.5)
print (a)
``````

1

``````a = np.arange(start, stop+step, step)
``````

Octave (Matlab) 版本给出了这种情况的 9 个值：

``````clc
start=0
stop=1.2
step=1/7
a = start : step : stop
length(a)
``````

``````start = 0
stop = 1.2000
step = 0.1429
a =

Columns 1 through 8:

0    0.1429    0.2857    0.4286    0.5714    0.7143    0.8571    1.0000

Column 9:

1.1429

ans = 9
``````

``````start = 0
stop = 1.2
step = 1 / 7
print("step", step)
a = np.arange(start, stop + step, step)
print(a)
print(a.size)
``````

``````step 0.14285714285714285
[0.         0.14285714 0.28571429 0.42857143 0.57142857 0.71428571
0.85714286 1.         1.14285714 1.28571429]
10
``````

（注意 1.28571429 > 1.2）

``````def arange_like_matlab_or_octave(a, b, srate):
k = []
i = 0
dt = 1 / srate
t = a + i * dt
while t <= b:
k.append(t)
i += 1
t = a + i * dt
return np.array(k)
``````

``````a = arange_like_matlab_or_octave(start, stop, 1 / step)
``````

``np.arange``
:

``````[0.         0.14285714 0.28571429 0.42857143 0.57142857 0.71428571
0.85714286 1.         1.14285714]
9
``````

0

Python 内置的

``xrange``

``````xrange(start, stop, step)
``````

``xrange``