
Python
的科学
|
417
>>> plain_list = [num * 3 for num in plain_list]
>>> plain_list
[0, 3, 6, 9]
这种批量操作同样适用于加法、减法、除法以及
NumPy
库中的其他函数。例如,可以使
用
zeros()
和
+
将数组的所有元素初始化为某个值。
>>> from numpy import *
>>> a = zeros((2, 5)) + 17.0
>>> a
array([[ 17., 17., 17., 17., 17.],
[ 17., 17., 17., 17., 17.]])
22.3.7
线性代数
NumPy
包含许多与线性代数相关的函数。例如,定义下列线性方程组:
4x + 5y = 20
x + 2y = 13
如何解方程?可以构建如下两个数组。
•
coefficients
(
x
和
y
的乘数)
•
dependent
变量(方程的右侧)
>>> import numpy as np
>>> coefficients = np.array([ [4, 5], [1, 2] ])
>>> dependents = np.array( [20, 13] )
现在,使用
linalg
模块的
solve()
函数:
>>> answers = np.linalg.solve(coefficients, dependents)
>>> answers
array([ -8.33333333, 10.66666667])
结果表明,