温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python2升级Python3(1):xrange

发布时间:2020-08-10 20:13:12 来源:ITPUB博客 阅读:151 作者:Ryan_Bai 栏目:编程语言

Python2升级到Python3的时候,我们会注意到xrange报错

这时建议将xrange换成range

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> type(range(6))
<type 'list'>

python2中,range的返回值是list,这意味着内存将会分布相应的长度的空间给list。

Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> type(range(6))
<class 'range'>

python3中返回值是一个对象,并没有将数据完全实例化,所以内存中只有一个对象的空间,对性能优化还是很有帮助的。

当然了你也可以在python3写一个xrange

def xrange(x):
    n=0
    while n<x:
        yield n
        n+=1

参考:https://blog.csdn.net/mvs2008/article/details/73693012 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI