range()真的会创建列表吗?

2024-05-14 08:03:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的教授和this guy都声称range创建了一个值列表。

"Note: The range function simply returns a list containing the numbers from x to y-1. For example, range(5, 10) returns the list [5, 6, 7, 8, 9]."

我认为这是不准确的,因为:

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

此外,访问由range创建的整数的唯一明显方法是遍历它们,这使我认为将range标记为列表是不正确的。


Tags: the列表rangefunctionthislistreturnsnote
3条回答

视情况而定。

在python-2.x中,range实际上创建了一个列表(这也是一个序列),而xrange创建了一个xrange对象,可用于遍历这些值。

另一方面,在python-3.x中,range创建一个iterable(或者更具体地说,一个序列)

在Python 2.x中,^{}返回一个列表,而在Python 3.x中,^{}返回一个类型为^{}的不可变序列。

Python2.x:

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

Python3.x:

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

在Python2.x中,如果您想要获得一个iterable对象,比如在Python3.x中,您可以使用^{}函数,它返回一个类型为^{}的不可变序列。

Python 2.x中xrangerange的优势:

The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with break).

注意:

Furthermore, the only apparent way to access the integers created by range() is to iterate through them,

没有。由于Python 3中的range对象是不可变的序列,因此它们也支持索引。引用range函数文档

Ranges implement all of the common sequence operations except concatenation and repetition

...

Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices.

例如

>>> 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 islice
numbers = 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.

如果使用的python版本是2.x,则range会创建一个列表。 在这个场景中,只有当它的引用不止一次时,才使用范围,否则使用xrange,xrange通过redusing内存使用量来创建一个生成器,有时还使用time as lazy方法。

在python 3.x中没有x range,而是range代表python 2.x的xrange

参考问题 What is the difference between range and xrange functions in Python 2.X?

相关问题 更多 >

    热门问题