黑白Python Range()与Numpy.arange()函数有什么区别?

我在网络搜索中了解到numpy.arange比python range函数占用更少的空间。但是我尝试过 在下面使用它给我不同的结果。

import sys

x = range(1,10000)
print(sys.getsizeof(x))  # --> Output is 48

a = np.arange(1,10000,1,dtype=np.int8)
print(sys.getsizeof(a))  # --> OutPut is 10095

有人可以解释吗?

评论
Dear
Dear

the range type constructor creates range objects, which represent sequences of integers with a start, stop, and step in a space efficient manner, calculating the values on the fly.

np.arange function returns a numpy.ndarray object, which is essentially a wrapper around a primitive array. This is a fast and relatively compact representation, compared to if you created a python list, so list(range(N)), but range objects are more space efficient, and indeed, take constant space, so for all practical purposes, range(a) is the same size as range(b) for any integers a, b

As an aside, you should take care interpreting the results of sys.getsizeof, you must understand what it is doing. So do not naively compare the size of Python lists and numpy.ndarray, for example.

Perhaps whatever you read was referring to Python 2, where range returned a list. List objects do require more space than numpy.ndarray objects, generally.

点赞
评论