gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:34:51 27 4
gpt4 key购买 nike

我的教授和 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 标记为列表是不正确的。

最佳答案

在 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函数,返回类型为 xrange 的不可变序列.

xrange 在 Python 2.x 中相对于 range 的优势:

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。但是,它会无限运行。你能说出原因吗?

解决方案

因为 range 返回一个不可变的sequence,而不是一个迭代器对象。因此,每当对 range 对象执行 islice 时,它总是从头开始。将其视为不可变列表的直接替代品。现在问题来了,你将如何解决它?它很简单,你只需要从中得到一个迭代器。简单地改变

numbers = range(100)



numbers = iter(range(100))

现在,numbers 是一个迭代器对象,它会记住它之前迭代了多长时间。所以,当 islice 迭代它时,它只是从它之前结束的地方开始。

关于python - range() 真的会创建列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23221025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com