我在网络搜索中了解到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
有人可以解释吗?
我在网络搜索中了解到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
有人可以解释吗?
the
range
type constructor createsrange
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 anumpy.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 pythonlist
, solist(range(N))
, butrange
objects are more space efficient, and indeed, take constant space, so for all practical purposes,range(a)
is the same size asrange(b)
for any integers a, bAs 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 thannumpy.ndarray
objects, generally.