今天网上学习了一下arange和range的区别,个人比较侧重于应用,但是找了两篇相关文章并没有明确说明,所以只能自己尝试了一下。
首先来说一下两者的相同点:
两者都是半开半闭的函数,对于生成一个有序数组,都是很简单方便的,示例如下(终端调试,代码不可直接复制)
from numpy import arange >>> s = arange(10) >>> f = range(10) >>> type(s)>>> type(f)
不同点:
1.range可以直接使用,但是arange需要从numpy引用,所以以上部分增加了一句 from numpy import arange。
2.两者可生成的步长不一致,range的步长只能是整数,arange的步长可以是小数。
2.arange是用于统计绘图,可以直接用于生成函数结果,但是range不可以,但是两者都可以直接用来绘图,具体原因不知道怎么说,详见代码(图片不做记录matplotlib.lines.Line2D表示生成图像成功):
>>> range(0,10,0.1) Traceback (most recent call last): File "", line 1, in TypeError: 'float' object cannot be interpreted as an integer >>> range(0,10,1) range(0, 10) >>> arange(0,10,0.1) array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5. , 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6. , 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7. , 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8. , 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9. , 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9]) >>> arange(0,10) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> x = range(10) >>> y = 2*x Traceback (most recent call last): File " ", line 1, in TypeError: unsupported operand type(s) for *: 'int' and 'range' >>> y= f*2 Traceback (most recent call last): File " ", line 1, in TypeError: unsupported operand type(s) for *: 'range' and 'int' >>> y= s*2 >>> y array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) >>> matplotlib.pyplot(x,y) Traceback (most recent call last): File " ", line 1, in TypeError: 'module' object is not callable >>> import matplotlib.pyplot as plt >>> plt(x,y) Traceback (most recent call last): File " ", line 1, in TypeError: 'module' object is not callable >>> plt.plot(x,y) [ ] >>> plt.show() >>> plt.plot(x,y) [ ] >>> plt.show() >>>



