python创建矩阵

创建二维数组的办法

  1. 直接创建(不推荐)
  2. 列表生产式法(可以去列表生成式 - 廖雪峰的官方网站学习)
  3. 使用模块numpy创建

举个栗子:

创建一个3*3矩阵,并计算主对角线元素之和。


import numpy as np
a=np.random.randint(1,100,9).reshape(3,3) #生成形状为9的一维整数数组
a=np.random.randint(1,100,(3,3)) #上面的语句也可以改为这个
print(a)
(m,n)=np.shape(a) # (m,n)=(3,3)
sum=0
for i in range(m):
for j in range(n):
if i==j:
sum+=a[i,j]
print(sum)

  

其中一次输出:
[[96 42 16]
 [19 14 92]
 [39 29 95]]
205

numpy中random:

  • numpy.random.randint(low, high=None, size=None, dtype='l'):生成一个整数或N维整数数组,取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。
#numpy.random.randint(low, high=None, size=None, dtype='l')
import numpy as np
#low=2
np.random.randint(2)#生成一个[0,2)之间随机整数
#low=2,size=5
np.random.randint(2,size=5)#array([0, 1, 1, 0, 1])
#low=2,high=2
#np.random.randint(2,2)#报错,high必须大于low
#low=2,high=6
np.random.randint(2,6)#生成一个[2,6)之间随机整数
#low=2,high=6,size=5
np.random.randint(2,6,size=5)#生成形状为5的一维整数数组
#size为整数元组
np.random.randint(2,size=(2,3))#生成一个2x3整数数组,取数范围:[0,2)随机整数
np.random.randint(2,6,(2,3))#生成一个2x3整数数组,取值范围:[2,6)随机整数
#dtype参数:只能是int类型
np.random.randint(2,dtype='int32')
np.random.randint(2,dtype=np.int32)

reshape()用法

arange()用于生成一维数组 
reshape()将一维数组转换为多维数组

举个栗子:

import numpy as np

print('默认一维为数组:', np.arange(5))
print('自定义起点一维数组:',np.arange(1, 5))
print('自定义起点步长一维数组:',np.arange(2, 10, 2))
print('二维数组:', np.arange(8).reshape((2, 4)))
print('三维数组:', np.arange(60).reshape((3, 4, 5)))

print('指定范围三维数组:',np.random.randint(1, 8, size=(3, 4, 5)))
默认一维数组: [0 1 2 3 4]
自定义起点一维数组: [1 2 3 4]
自定义起点步长一维数组: [2 4 6 8]
二维数组: [[0 1 2 3]
 [4 5 6 7]]
三维数组: [[[ 0  1  2  3  4]
  [ 5  6  7  8  9]
  [10 11 12 13 14]
  [15 16 17 18 19]]

 [[20 21 22 23 24]
  [25 26 27 28 29]
  [30 31 32 33 34]
  [35 36 37 38 39]]

 [[40 41 42 43 44]
  [45 46 47 48 49]
  [50 51 52 53 54]
  [55 56 57 58 59]]]
指定范围三维数组: [[[2 3 2 1 5]
  [6 5 5 6 7]
  [4 4 6 5 3]
  [2 2 3 5 6]]

 [[2 1 2 4 4]
  [1 4 2 1 4]
  [4 4 3 4 2]
  [4 1 4 4 1]]

 [[6 2 2 7 6]
  [2 6 1 5 5]
  [2 6 7 2 1]
  [3 3 1 4 2]]]
[[[3 3 5 6]
  [2 1 6 6]
  [1 1 3 5]]

 [[7 6 5 3]
  [5 6 5 4]
  [6 5 7 1]]]

shape()用法

查看矩阵或者数组的维数

建立一个3×3的单位矩阵e, e.shape为(3,3)

参考博文:https://blog.csdn.net/kancy110/article/details/69665164

    行走菜鸟界的小辣鸡~

原文地址:https://www.cnblogs.com/pipiyan/p/10445948.html