栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

211013python3 arange和range的区别

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

211013python3 arange和range的区别

今天网上学习了一下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()
>>>
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/321528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号