首先解答上一篇文章中使用with关键字让你的Python代码更加Pythonic最后的习题,该题答案是False,原因在于内置函数sorted()的参数reverse=True时表示降序排序,而内置函数reversed()是逆序或者翻转(首尾交换),二者之间没有任何关系。
--------------------分割线-------------------
Python扩展库numpy提供了大量的矩阵运算,本文进行详细描述。
>>> import numpy as np
>>> a_list = [3, 5, 7]
# 创建矩阵
>>> a_mat = np.matrix(a_list) >>> a_mat matrix([[3, 5, 7]])
# 矩阵转置
>>> a_mat.T matrix([[3], [5], [7]])
# 矩阵形状
>>> a_mat.shape (1, 3)
# 元素个数
>>> a_mat.size 3
# 创建矩阵
>>> b_mat = np.matrix((1, 2, 3)) >>> b_mat matrix([[1, 2, 3]])
# 矩阵相乘
>>> a_mat * b_mat.T matrix([[34]])
# 元素平均值
>>> a_mat.mean() 5.0
# 所有元素之和
>>> a_mat.sum() 15
# 最大值
>>> a_mat.max() 7
# 横向最大值
>>> a_mat.max(axis=1) matrix([[7]])
# 纵向最大值
>>> a_mat.max(axis=0) matrix([[3, 5, 7]])
# 创建二维矩阵
>>> c_mat = np.matrix([[1, 5, 3], [2, 9, 6]]) >>> c_mat matrix([[1, 5, 3], [2, 9, 6]])
# 纵向排序后的元素序号
>>> c_mat.argsort(axis=0) matrix([[0, 0, 0], [1, 1, 1]], dtype=int64)
# 横向排序后的元素序号
>>> c_mat.argsort(axis=1) matrix([[0, 2, 1], [0, 2, 1]], dtype=int64)
>>> d_mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 矩阵对角线元素
>>> d_mat.diagonal() matrix([[1, 5, 9]])
# 矩阵平铺
>>> d_mat.flatten() matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
# 特征值与特征向量
>>> np.linalg.eig([[1,1],[2,2]]) (array([ 0., 3.]), array([[-0.70710678, -0.4472136 ], [ 0.70710678, -0.89442719]]))
>>> x = np.matrix([[1,2], [3,4]])
# 逆矩阵
>>> y = np.linalg.inv(x) >>> x * y matrix([[ 1.00000000e+00, 1.11022302e-16], [ 0.00000000e+00, 1.00000000e+00]]) >>> y * x matrix([[ 1.00000000e+00, 4.44089210e-16], [ 0.00000000e+00, 1.00000000e+00]])
>>> d_mat = np.matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> e, v = np.linalg.eig(d_mat) >>> v*np.diag(e)*np.linalg.inv(v) matrix([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]])
# 协方差
>>> np.cov([1,1,1,1,1]) array(0.0) >>> x = [-2.1, -1, 4.3] >>> y = [3, 1.1, 0.12] >>> X = np.vstack((x,y))
# 协方差
>>> print(np.cov(X)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print(np.cov(x, y)) [[ 11.71 -4.286 ] [ -4.286 2.14413333]] >>> print(np.cov(x)) 11.709999999999999
# 二维矩阵
>>> x = np.matrix(np.arange(0,10).reshape(2,5)) >>> x matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])
# 所有元素之和
>>> x.sum() 45
# 纵向求和
>>> x.sum(axis=0) matrix([[ 5, 7, 9, 11, 13]])
# 横向求和
>>> x.sum(axis=1) matrix([[10], [35]])
# 平均值
>>> x.mean() 4.5 >>> x.mean(axis=1) matrix([[ 2.], [ 7.]]) >>> x.mean(axis=0) matrix([[ 2.5, 3.5, 4.5, 5.5, 6.5]])
------------------分割线----------------
今日习题:表达式10 ** 2 ** 3的值是什么,原因是什么?