Python3 列表,数组,矩阵的相互转换的方法示例

yipeiwu_com6年前Python基础

在使用列表、数组和矩阵的过程中,经常需要相互转换。特此总结相互间转换的过程及结果,供大家参考。

第三方包:numpy    

  import numpy as np
  mylist = [[1, 2, 3], [4, 5, 6]] # 列表
  print(type(mylist))
  print(mylist, end='\n\n')
 
  myarray = np.array(mylist) # 列表转数组
  print(type(myarray))
  print(myarray, end="\n\n")
 
  mymatrix = np.mat(mylist) # 列表转矩阵
  print(type(mymatrix))
  print(mymatrix, end='\n\n')
 
  MatToArray = np.array(mymatrix) # 矩阵转数组
  print(type(MatToArray))
  print(MatToArray, end='\n\n')
 
  ArrayToMat = np.mat(myarray) # 数组转矩阵
  print(type(ArrayToMat))
  print(ArrayToMat, end='\n\n')
 
  MatToList1 = mymatrix.tolist() # 矩阵转列表
  print(type(MatToList1))
  print(MatToList1)
  MatToList2 = list(mymatrix) # 注意点1
  print(type(MatToList2))
  print(MatToList2, end='\n\n')
 
  ArrayToList1 = myarray.tolist() # 矩阵转列表
  print(type(ArrayToList1))
  print(ArrayToList1)
  ArrayToList2 = list(myarray) # 注意点2
  print(type(ArrayToList2))
  print(ArrayToList2)

函数运行结果显示如下。注意一点是,最后的矩阵和数组转换成列表形式,用list()是将矩阵和数组整体转换成列表。如果要将其转换成基本的列表形式,则需要使用<array>.tolist() 或者 <matrix>.tolist()来转换。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python代码制作configure文件示例

在lua中,一直用lua作为config文件,或承载数据的文件 - 好处是lua本身就很好阅读,然后无需额外写解析的代码,还支持在configure文件中读环境变量,条件判断等。 在lu...

python 并发编程 非阻塞IO模型原理解析

python 并发编程 非阻塞IO模型原理解析

非阻塞IO(non-blocking IO) Linux下,可以通过设置socket使其变为non-blocking。当对一个non-blocking socket执行读操作时,流程是...

Python实现获取邮箱内容并解析的方法示例

本文实例讲述了Python实现获取邮箱内容并解析的方法。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- from email.parser impo...

Python生成不重复随机值的方法

本文实例讲述了Python生成不重复随机值的方法。分享给大家供大家参考。具体分析如下: 这里从一列表中,生成不重复的随机值 算法实现如下: import random total =...

windows下wxPython开发环境安装与配置方法

安装文件准备: 安装文件 下载地址 python-2.6.2.msi http://www.py...