python如何输入矩阵

Python041

python如何输入矩阵,第1张

使用numpy创建矩阵有2种方法,一种是使用numpy库的matrix直接创建,另一种则是使用array来创建。

首先导入numpy:

(1)import numpy

(2)from numpy import *

(3)import numpy as np

相关推荐:《Python基础教程》

然后分别用上面说的2种方法来分别构建一个4×3的矩阵,如图:

你得先安装numpy库,矩阵(ndarray)的shape属性可以获取矩阵的形状(例如二维数组的行列),获取的结果是一个元组,因此相关代码如下:

import numpy as np

x = np.array([[1,2,5],[2,3,5],[3,4,5],[2,3,6]])

# 输出数组的行和列数

print x.shape  # (4, 3)

# 只输出行数

print x.shape[0] # 4

# 只输出列数

print x.shape[1] # 3