什么是<class 'range'>

问题描述 投票:0回答:3

Python3:

string = range(10)
print("{}".format(type(string)))

输出:

class 'range'

我只是对这个班级的“范围”感到好奇。 谁能解释一下吗?

但是在Python2中:

输出:

class 'list'

嗯,这是不言自明的

python python-2.7 python-3.x range
3个回答
5
投票

在 Python 2 中

range(val)
生成列表的实例,它只是一个函数。从而
type(range(10))
将返回
class 'list'

在 Python

3
中,
range
相当于 Python 2 中的
xrange
,它返回名为
range
的新类的实例。有关 Python 2/3 之间的更多更改/差异,请参阅
PEP 3100


4
投票

Python 3 添加了一个新的

range
类来有效处理“不可变的数字序列”(类似于 Python 2 的
xrange
)。 Python 2 没有这样的范围类,因此
range
函数仅返回一个列表。


0
投票

python3 的主要区别(取自 https://docs.python.org/3/library/stdtypes.html#range

范围类型相对于常规列表或元组的优点是 范围对象将始终占用相同(少量)的内存,不 不管它代表的范围的大小(因为它只存储 开始、停止和步骤值,计算单个项目和 根据需要划分子范围)。

© www.soinside.com 2019 - 2024. All rights reserved.