Python Equivalent of MATLAB's colon operator

2019-07-20 08:03发布

问题:

In MATLAB I can create monotonically spaced vectors as in the examples below using the :, colon, operator. How can I do this in Python in a similarly concise manner?

>> x=1:10
x =
     1     2     3     4     5     6     7     8     9    10

or

>> x=0:2:10
x =
     0     2     4     6     8    10

回答1:

there is range

range([start], stop[, step])

[] shows optional arguments. Default ranges starts with zero



回答2:

@karakfa is right in that this is the way to create a simple list.

Matlab's vectors and matrices offer vectorised computation, though, and if that's what you need, you should probably use numpy.array:

>>> import numpy
>>> numpy.arange(1, 11)
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])


回答3:

You should use

list(range(0,11,2))

because range is an immutable iterable object.