栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

range()是否真的创建列表?

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

range()是否真的创建列表?

在Python
2.x中,

range
返回一个列表,但在Python
3.x中,
range
返回一个不可变序列,类型为
range


Python 2.x:

>>> type(range(10))<type 'list'>>>> type(xrange(10))<type 'xrange'>

Python 3.x:

>>> type(range(10))<class 'range'>

在Python 2.x中,如果要获得可迭代对象(如在Python
3.x中),则可以使用

xrange
function,该函数返回type的不可变序列
xrange

优势

xrange
超过
range
在Python 2.x的:

xrange()
over的优点
range()
是最小的(因为
xrange()
在要求输入值时仍必须创建值),除非在内存不足的机器上使用了很大的范围或从未使用过所有范围的元素(例如当循环被使用时)。通常以中断终止)。

注意:

此外,访问由创建的整数的唯一明显方法

range()
是遍历它们,

不。由于

range
Python 3中的对象是不可变的序列,因此它们也支持索引。引用
range
功能文档,

范围实现除连接和重复之外的所有通用序列操作

范围对象实现

collections.abc.Sequence
ABC,并提供诸如包含测试,
元素索引查找 ,切片和对负索引的支持等功能。

例如,

>>> range(10, 20)[5]15>>> range(10, 20)[2:5]range(12, 15)>>> list(range(10, 20)[2:5])[12, 13, 14]>>> list(range(10, 20, 2))[10, 12, 14, 16, 18]>>> 18 in range(10, 20)True>>> 100 in range(10, 20)False

通过不变的

range
序列,所有这些都是可能的。


最近,我遇到了一个问题,我认为将其包含在此处是适当的。考虑此Python 3.x代码

from itertools import islicenumbers = range(100)items = list(islice(numbers, 10))while items:    items = list(islice(numbers, 10))    print(items)

人们会希望此代码将每十个数字作为列表打印,直到99。但是,它将无限运行。你能解释为什么吗?

Because the

range
returns an immutable sequence , not an iterator
object. So, whenever
islice
is done on a
range
object, it always starts
from the beginning. Think of it as a drop-in replacement for an immutable
list. Now the question comes, how will you fix it? Its simple, you just have
to get an iterator out of it. Simply change

numbers = range(100)

to

numbers = iter(range(100))

Now,

numbers
is an iterator object and it remembers how long it has been
iterated before. So, when the
islice
iterates it, it just starts from the
place where it previously ended.



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639134.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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