Python中的二维数组实例(list与numpy.array)

yipeiwu_com6年前Python基础

关于python中的二维数组,主要有list和numpy.array两种。

好吧,其实还有matrices,但它必须是2维的,而numpy arrays (ndarrays) 可以是多维的。

我们主要讨论list和numpy.array的区别:

我们可以通过以下的代码看出二者的区别

>>import numpy as np
>>a=[[1,2,3],[4,5,6],[7,8,9]]
>>a
[[1,2,3],[4,5,6],[7,8,9]]
>>type(a)
<type 'list'>
>>b=np.array(a)"""List to array conversion"""
>>type(b)
<type 'numpy.array'>
>>b
array=([[1,2,3],
    [4,5,6],
    [7,8,9]])

list对应的索引输出情况:

>>a[1][1]
5
>>a[1]
[4,5,6]
>>a[1][:]
[4,5,6]
>>a[1,1]"""相当于a[1,1]被认为是a[(1,1)],不支持元组索引"""
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>a[:,1]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

numpy.array对应的索引输出情况:

>>b[1][1]
5
>>b[1]
array([4,5,6])
>>b[1][:]
array([4,5,6])
>>b[1,1]
5
>>b[:,1]
array([2,5,8])

由上面的简单对比可以看出, numpy.array支持比list更多的索引方式,这也是我们最经常遇到的关于两者的区别。此外从[Numpy-快速处理数据]上可以了解到“由于list的元素可以是任何对象,因此列表中所保存的是对象的指针。

这样为了保存一个简单的[1,2,3],有3个指针和3个整数对象。”

以上这篇Python中的二维数组实例(list与numpy.array)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

itchat接口使用示例

有关itchat接口的知识,小编是初步学习,这里先给大家分享一段代码用法示例。 sudo pip3 install itchat 今天用了下itchat接口,从url=”https://...

Python中将字典转换为XML以及相关的命名空间解析

尽管 xml.etree.ElementTree 库通常用来做解析工作,其实它也可以创建XML文档。 例如,考虑如下这个函数: from xml.etree.ElementTree...

Python将DataFrame的某一列作为index的方法

下面代码实现了将df中的column列作为index df.set_index(["Column"], inplace=True) 以上这篇Python将DataFrame的某一...

python docx 中文字体设置的操作方法

最近用到了docx生成word文档,docx本身用起来很方便,自带的各种样式都很好看,美中不足的就是对中文的支持不够好。在未设置中文字体的时候,生成的文档虽然可以显示中文,但是笔画大小不...

python机器学习库xgboost的使用

python机器学习库xgboost的使用

1.数据读取 利用原生xgboost库读取libsvm数据 import xgboost as xgb data = xgb.DMatrix(libsvm文件) 使用sk...