range()和xrange()是两个函数,可用于在 对于 Python中的循环。在Python3中没有xrange,但range函数的行为与Python2中的xrange类似。如果要编写同时在Python 2和Python 3上运行的代码,应该使用range()。
null
- 范围() –返回一个范围对象(iterable的一种类型)。
- xrange() –此函数返回 生成器对象 只能通过循环来显示数字。唯一的特定范围是按需显示的,因此称为“ 惰性评估 “.
两者都以不同的方式实现,并具有与之相关的不同特征。比较的要点是:
- 返回类型
- 记忆力
- 操作使用
- 速度
返回类型
range()返回- 范围 对象 xrange()返回- xrange() 对象
python
# Python code to demonstrate range() vs xrange() # on basis of return type # initializing a with range() a = range ( 1 , 10000 ) # initializing a with xrange() x = xrange ( 1 , 10000 ) # testing the type of a print ( "The return type of range() is : " ) print ( type (a)) # testing the type of x print ( "The return type of xrange() is : " ) print ( type (x)) |
输出:
The return type of range() is : <type 'list'>The return type of xrange() is : <type 'xrange'>
记忆力
存储 范围 由range()创建 需要更多的记忆 与使用xrange()存储范围的变量相比。其基本原因是range()的返回类型是list,而xrange()是xrange()对象。
python
# Python code to demonstrate range() vs xrange() # on basis of memory import sys # initializing a with range() a = range ( 1 , 10000 ) # initializing a with xrange() x = xrange ( 1 , 10000 ) # testing the size of a # range() takes more memory print ( "The size allotted using range() is : " ) print (sys.getsizeof(a)) # testing the size of x # xrange() takes less memory print ( "The size allotted using xrange() is : " ) print (sys.getsizeof(x)) |
输出:
The size allotted using range() is : 80064The size allotted using xrange() is : 40
操作使用
当range()返回列表时 可以 可以在列表上应用,也可以在列表上使用。另一方面,当xrange()返回xrange对象时,与列表关联的操作 不能 这是一个缺点。
python
# Python code to demonstrate range() vs xrange() # on basis of operations usage # initializing a with range() a = range ( 1 , 6 ) # initializing a with xrange() x = xrange ( 1 , 6 ) # testing usage of slice operation on range() # prints without error print ( "The list after slicing using range is : " ) print (a[ 2 : 5 ]) # testing usage of slice operation on xrange() # raises error print ( "The list after slicing using xrange is : " ) print (x[ 2 : 5 ]) |
错误:
Traceback (most recent call last): File "1f2d94c59aea6aed795b05a19e44474d.py", line 18, in print (x[2:5])TypeError: sequence index must be integer, not 'slice'
输出:
The list after slicing using range is : [3, 4, 5]The list after slicing using xrange is :
速度
由于xrange()只计算仅包含惰性计算所需值的生成器对象,因此 更快 在实现中,比range()更重要。
要点:
- 如果要编写同时在Python 2和Python 3上运行的代码,请使用range(),因为Python 3中不推荐使用xrange函数。
- 如果对同一序列多次迭代,range()会更快。
- xrange()每次都必须重建整数对象,但range()将具有真正的整数对象。(但在记忆方面,它的表现总是更差)
范围() | xrange() |
---|---|
返回整数列表。 | 返回生成器对象。 |
执行速度较慢 | 执行速度更快。 |
需要更多内存,因为它会将整个元素列表保留在内存中。 | 占用更少的内存,因为它一次只在内存中保留一个元素。 |
当它返回一个列表时,可以执行所有算术运算。 | 无法在xrange()上执行此类操作。 |
在python 3中,不支持xrange()。 | 在python 2中,xrange()用于迭代for循环。 |
本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END