Python中的二维数组实例(list与numpy.array)
关于python中的二维数组,主要有list和numpy.array两种。
好吧,其实还有matrices,但它必须是2维的,而numpy arrays (ndarrays) 可以是多维的。
我们主要讨论list和numpy.array的区别:
{ a = [ [1, 2, 3], [4, 5, 6] ] } 表示的是一个2*3的二维数组
我们可以通过以下的代码看出二者的区别
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>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对应的索引输出情况:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | >>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对应的索引输出情况:
1 2 3 4 5 6 7 8 9 10 | >>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个整数对象。”
原文链接:https://www.jb51.net/article/138215.htm