您的位置:首页 > 编程语言 > Python开发

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

2016-05-18 16:53 656 查看
关于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个整数对象。”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: