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

来源:互联网 发布:linux启动jenkins 编辑:程序博客网 时间:2024/06/05 05:56

出处:https://hsh.blog.ustc.edu.cn/2015/04/24/238/

关于python中的二维数组,主要有list和numpy.array两种。上次课间阿C问我两者的区别,但是说实话,我在python方面也仅是入门,只会修改已有的代码和写一些基础的代码。关于这些细节其实也不是很清楚。这两天刚好也遇见了类似的问题,所以趁着跑程序的空总结一下。

 

其实在python下运行几个示例就可以看出两者的区别(这也是是我写python程序的常态>_<

In [2]:
a = [[1, 2 , 3],     [4, 5, 6]]import numpy as npb = np.array(a)print type(a)print aprint type(b)print b
<type 'list'>[[1, 2, 3], [4, 5, 6]]<type 'numpy.ndarray'>[[1 2 3] [4 5 6]]
In [4]:
print a[1][2]print a[1][:]
6[4, 5, 6]
补充:print a[:][1]
[4, 5, 6]   为什么答案跟a[1][:]一样,之前一直不解?以为答案会是[2,5]
其实[:]代表取所有,相当于复制整个list,a[:][1]表示先复制整个list之后取第二个元素,也就是[4,5,6]; a[1][:]表示先取第二个元素然后复制第二个元素。
为了验证 取
a[:][1][2],  答案果然是6.
In [5]:
print a[1,2]
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-5-9da16148905d> in <module>()----> 1 print a[1,2]TypeError: list indices must be integers, not tuple
In [6]:
print a[1, :]
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-6-f921c5f2e22f> in <module>()----> 1 print a[1, :]TypeError: list indices must be integers, not tuple
In [7]:
print b[1][2]print b[1][:]print b[1, 2]print b[1, :]
6[4 5 6]6[4 5 6]

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

此外可以通过dir(a)和dir(b)分别查看两者更详细的属性。