NumPy 数组专为处理多维数值数据而设计,额外支持任意对象数组。它们以方便的语法提供快速矢量化操作。
>>> x = numpy.arange(4).reshape((2, 2))
>>> x
array([[0, 1],
[2, 3]])
>>> x.T # Transpose.
array([[0, 2],
[1, 3]])
>>> x.max()
3
>>> x * 4
array([[ 0, 4],
[ 8, 12]])
>>> x[:, 1] # Slice to select the second column.
array([1, 3])
>>> x[:, 1] *= 2
>>> x
array([[0, 2],
[2, 6]])
>>> timeit.timeit('x * 5',
... setup='import numpy; x = numpy.arange(1000)',
... number=100000)
0.4018515302670096
>>> timeit.timeit('[item*5 for item in x]',
... setup='x = range(1000)',
... number=100000)
8.542360042395984
相比之下,列表基本上面向一维数据。您可以有一个列表列表,但这不是二维列表。您不能方便地将 2D 数据集的最大值表示为列表的列表;在其上调用max 将按字典顺序比较列表并返回一个列表。列表适用于对象的同质序列,但如果你在做数学,你想要 numpy,你想要 ndarrays。