NumPy arange()

arange()方法根据间隔创建具有等间距元素的数组。

示例

import numpy as np

# create an array with elements from 5 to 10 array1 = np.arange(5, 10)
print(array1) # Output: [5 6 7 8 9]

arange() 语法

arange()的语法是

numpy.arange(start = 0, stop, step = 1, dtype = None)

arange() 参数

arange()方法接受以下参数

  • start(可选)- 间隔范围的起始值(intreal
  • stop - 间隔范围的结束值(不包含)(intreal
  • step(可选)- 间隔的步长(intreal
  • dtype(可选)- 输出数组的类型(dtype

注意事项

  • step不能为零。否则,您将收到一个ZeroDivisionError
  • 如果省略dtypearange()将根据其他参数的类型来确定数组元素的类型。
  • arange()中,stop值是不包含在内的。

arange() 返回值

arange()方法返回一个等间距值的数组。


示例 1:使用 arange 创建一维数组

import numpy as np

# create an array with first five elements array1 = np.arange(5) # create an array with elements from 5 to 10(exclusive) array2 = np.arange(5, 10) # create an array with elements from 5 to 15 with stepsize 2 array3 = np.arange(5, 15, 2)
print(array1) print(array2) print(array3)

输出

[0 1 2 3 4]
[5 6 7 8 9]
[ 5  7  9 11 13]

注意:

如果只传递一个参数,它代表stop值,并且start = 0step = 1

如果传递两个参数,它们代表startstop值,并且step = 1


示例 2:使用 arange 创建浮点数一维数组

import numpy as np

# create an array with elements from 0 to 1 with stepsize 0.2
array1 = np.arange(0, 1, 0.2)

print(array1)

输出

[0.  0.2 0.4 0.6 0.8]

示例 3:在 arange 中传递负值参数

import numpy as np

# create an array with elements from -5 to 5 with step size 2 array1 = np.arange(-5, 5, 2) # create an array with elements from -15 to -5 with step size 2 array2 = np.arange(-15, -5, 2) # create an array with elements from 15 to 5 with step size -2 array3 = np.arange(15, 5, -2)
print(array1) print(array2) print(array3)

输出

[-5 -3 -1  1  3]
[-15 -13 -11  -9  -7]
[15 13 11  9  7]

注意

  • 当在numpy.arange()startstop值中传递负整数时,它们与正整数的处理方式相同。
  • 将负整数作为step大小传递会创建一个降序排列的数组。

arange 和 linspace 的主要区别

np.arange()np.linspace()都是用于生成数值序列的NumPy函数,但它们在行为上存在一些差异。

  • arange()根据给定的step大小从startstop生成一系列值,而linspacestartstop生成num个等间距的值。
  • arange()不包含stop值,而linspace包含stop值,除非通过endpoint = False另外指定。

让我们看一个例子。

import numpy as np

# elements between 10 and 40 with stepsize 4 array1 = np.arange(10, 50 ,4) # generate 4 elements between 10 and 40 array2 = np.linspace(10, 50 ,4)
print('Using arange:',array1) # doesn't include 50 print('Using linspace:',array2) # includes 50

输出

Using arange: [10 14 18 22 26 30 34 38 42 46]
Using linspace: [10.         23.33333333 36.66666667 50.        ]

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战