在 NumPy 中返回給定區間和步長內的等間距值


使用 **numpy.arange()** 方法建立一個包含整數元素的陣列。第一個引數是“**start**”,即區間的起點。第二個引數是“**end**”,即區間的終點。第三個引數是步長,即值之間的間距。這裡的預設步長為 2。

值在半開區間 [start, stop) 內生成。對於整數引數,該函式等效於 Python 內建的 range 函式,但返回的是 ndarray 而不是列表。

stop 是區間的終點。區間不包含此值,但在步長不是整數且浮點舍入影響 out 長度的一些情況下除外。步長是值之間的間距。對於任何輸出 out,這是兩個相鄰值之間的距離,out[i+1] - out[i]。預設步長為 1。如果步長作為位置引數指定,則也必須給出 start。

步驟

首先,匯入所需的庫:

import numpy as np

使用 numpy.arange() 方法建立一個包含整數元素的陣列。這裡我們將步長設定為 2:

arr = np.arange(15, 30, step = 2)
print("Array...
", arr)

獲取陣列的型別:

print("
Array type...
", arr.dtype)

獲取陣列的維度:

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀:

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素個數:

print("
Number of elements in the Array...
",arr.size)

示例

import numpy as np

# Creating an array with int elements using the numpy.arange() method
# The 1st parameter is the "start" i.e. the start of the interval
# The 2nd parameter is the "end" i.e. the end of the interval
# The 3rd parameter is step size i.e. the spacing between values. The default step size is 1
# We have set the step size to 2 here
arr = np.arange(15, 30, step = 2)
print("Array...
", arr) # Get the array type print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Number of elements in the Array...
",arr.size)

輸出

Array...
[15 17 19 21 23 25 27 29]

Array type...
int64

Array Dimensions...
1

Our Array Shape...
(8,)

Number of elements in the Array...
8

更新於:2022年2月10日

700 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告
© . All rights reserved.