天天看點

Python 中的range(),arange()函數

Python 中的range(),以及numpy包中的arange()函數

range()函數

*函數說明: range(start, stop[, step]) -> range object,根據start與stop指定的範圍以及step設定的步長,生成一個序列。

參數含義:start:計數從start開始。預設是從0開始。例如range(5)等價于range(0, 5);

end:技術到end結束,但不包括end.例如:range(0, 5) 是[0, 1, 2, 3, 4]沒有5

scan:每次跳躍的間距,預設為1。例如:range(0, 5) 等價于 range(0, 5, 1)

函數傳回的是一個range object *

例子:

>>> range(0,5) 			 	#生成一個range object,而不是[0,1,2,3,4] 
range(0, 5)   
>>> c = [i for i in range(0,5)] 	 #從0 開始到4,不包括5,預設的間隔為1
>>> c
[0, 1, 2, 3, 4]
>>> c = [i for i in range(0,5,2)] 	 #間隔設為2
>>> c
[0, 2, 4]

           
  • 若需要生成[ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
>>> range(0,1,0.1)    #range中的setp 不能使float
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    range(0,1,0.1)
TypeError: 'float' object cannot be interpreted as an integer

           

arrange()函數

函數說明:arange([start,] stop[, step,], dtype=None)根據start與stop指定的範圍以及step設定的步長,生成一個 ndarray。 dtype : dtype

The type of the output array. If

dtype

is not given, infer the data

type from the other input arguments.

>>> np.arange(3)
    array([0, 1, 2])
    >>> np.arange(3.0)
    array([ 0.,  1.,  2.])
    >>> np.arange(3,7)
    array([3, 4, 5, 6])
    >>> np.arange(3,7,2)
    array([3, 5])

           
>>> arange(0,1,0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])