对于任何设计数组的计算密集型任务,请使用NumPy库。
NumPy库的主要特性是为Python提供了数组对象,比标准Python的列表有着更好的性能表现,更加适合用做数学计算。
先展示一下对于基本的运算符,标准列表和NumPy的数组的差异如何
1>标准列表
>>> #Python lists
>>> x = [1, 2, 3, 4]
>>> y = [5, 6, 7, 8]
>>> x * 2
[1, 2, 3, 4, 1, 2, 3, 4]
>>> x + 10
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
x + 10
TypeError: can only concatenate list (not "int") to list
>>> x + y
[1, 2, 3, 4, 5, 6, 7, 8]
2>NumPy的数组
>>> #NumPy arrays
>>> import numpy as np
>>> ax = np.array([1, 2, 3, 4])
>>> ay = np.array([5, 6, 7, 8])
>>> ax * 2
array([2, 4, 6, 8])
>>> ax + 10
array([11, 12, 13, 14])
>>> ax + ay
array([ 6, 8, 10, 12])
>>> ax * ay
array([ 5, 12, 21, 32])
可以看