📜  如何创建一个间隔中等距数字的 NumPy 一维数组?

📅  最后修改于: 2022-05-13 01:54:36.888000             🧑  作者: Mango

如何创建一个间隔中等距数字的 NumPy 一维数组?

有时,我们需要制作不同类型的数组,例如 AP(等间距数字系列)、GP(指数间距数字系列)或 HP(倒数间距数字系列)来解决各种问题,尤其是在解决一些科学或天文问题,以减少计算。就预实现的代码而言, Python是最好的语言之一,并且几乎每次都出现在其中,但代价是处理速度。

NumPy 有一个名为 arange() 的内置方法,它能够创建一个给定整数类型(以字节为单位)的数组,数字之间的间距相等。

该函数将根据用户的需求返回一个数组。让我们看一些例子:

示例 1:创建一个从 0 到给定数字的简单数组

Python3
import numpy as np
 
# Here, the array has only one parameter,
# and that is the open ended limit of
# last number of the array
myArray = np.arange(8)
print(myArray)


Python3
import numpy as np
 
 
# This line has two parameters
# The first one is the closed and beginning limit
# The second one is the open and end limit
mySecondArray = np.arange(1, 6)
print(mySecondArray)


Python3
import numpy as np
 
# This line has two parameters
# The first one is the closed and beginning limit
# The second one is the open and end limit
# The third one is the steps(difference between
# two  elements in the array)
myThirdArray = np.arange(2, 12, 2)
print(myThirdArray)


Python3
import numpy as np
 
# This line has two parameters
# The first one is the closed and beginning limit
# The second one is the open and end limit
# The third one is the steps(difference between
# two  elements in the array)
myForthArray = np.arange(5, 101, 10, np.int32)
print(myForthArray)


输出:

[0 1 2 3 4 5 6 7]

示例 2:创建一个从给定数字开始到另一个数字的简单数组

Python3

import numpy as np
 
 
# This line has two parameters
# The first one is the closed and beginning limit
# The second one is the open and end limit
mySecondArray = np.arange(1, 6)
print(mySecondArray)

输出:

[1 2 3 4 5]

示例 3:创建一个从给定数字到具有给定间隔的另一个数字的数组。

Python3

import numpy as np
 
# This line has two parameters
# The first one is the closed and beginning limit
# The second one is the open and end limit
# The third one is the steps(difference between
# two  elements in the array)
myThirdArray = np.arange(2, 12, 2)
print(myThirdArray)

输出:

[ 2  4  6  8 10]

示例 4:我们使用 dtype 尤其是在我们想要处理图像或其他某种计算的情况下。

Python3

import numpy as np
 
# This line has two parameters
# The first one is the closed and beginning limit
# The second one is the open and end limit
# The third one is the steps(difference between
# two  elements in the array)
myForthArray = np.arange(5, 101, 10, np.int32)
print(myForthArray)

输出:

[ 5 15 25 35 45 55 65 75 85 95]