Python
中的list和array的不同之处
也可以直接改变属性array的形状,-1代表的是自己推算。这里并不是T, reshape(())也可以
python中的list是python的内置数据类型,list中的数据类不必相同的,而array的中的类型必须全部相同。在list中的数据类型保存的是数据的存放的地址,简单的说就是指针,并非数据,这样保存一个list就太麻烦了,例如list1=[1,2,3,'a']需要4个指针和四个数据,增加了存储和消耗cpu。
numpy中封装的array有很强大的功能,里面存放的都是相同的数据类型
运行结果:
创建:
array的创建:参数既可以是list,也可以是元组.使用对应的属性shape直接得到形状
也可以直接改变属性array的形状,-1代表的是自己推算。这里并不是T, reshape(())也可以
这里的reshape最终相当于是一个浅拷贝,也就是说还是和原来的书c使用相同的内存空间
array([[ 1, 2, 3], [ 4, 4, 5], [100, 100, 100], [100, 100, 100]])
前面在创建数组的时候并没有使用数据类型,这里我们也可以使用数据类型。默认的是int32.
前面在创建的时候我们都是使用的np.array()方法从tuple或者list转换成为array,感觉很是费劲,numpy自己提供了很多的方法让我们自己直接创建一个array.
[1 2 3 4 5 6 7 8 9] int32 [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] float64
np.arange(a,b,c)表示产生从a-b不包括b,间隔为c的一个array,数据类型默认是int32。但是linspace(a,b,c)表示的是把a-b平均分成c分,它包括b。
有时候我们需要对于每一个元素的坐标进行赋予不同的数值,可以使用fromfunction函数
array([ 2., 3., 4., 5., 2., 3., 4., 5., 2., 3.])fromfunction必须支持多维数组,所以他的第二个参数必须是一个tuple,只能是(10,),(10)是错误的。
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9.], [ 2., 4., 6., 8., 10., 12., 14., 16., 18.], [ 3., 6., 9., 12., 15., 18., 21., 24., 27.], [ 4., 8., 12., 16., 20., 24., 28., 32., 36.], [ 5., 10., 15., 20., 25., 30., 35., 40., 45.], [ 6., 12., 18., 24., 30., 36., 42., 48., 54.], [ 7., 14., 21., 28., 35., 42., 49., 56., 63.], [ 8., 16., 24., 32., 40., 48., 56., 64., 72.], [ 9., 18., 27., 36., 45., 54., 63., 72., 81.]])虽然说,这里提供了很多的直接产生array的方式,但是大部分情况我们都是会从list进行转换,因为在实际的处理中,我们需要从txt加载文件,那样直接读入的数据显示存放到list中,需要处理的时候我们转换到array,因为
array的设计更加符合我们的使用,涉及到矩阵的运算在使用mat,那么list主要就是用进行元素的索取。
上面的韩顺返回最终的数据就是最初的list数据集,再根据不同的处理需求是转化到array还是mat。其实array是mat的父类,能用mat的地方,array理论上都能传入。
元素访问:
上面是array的一维数组的访问方式,我们再来看看二维的处理方式
[[4 4 5]] [4 4 5][4 4 5] [[4 4 5]]5 [[ 4 4 5] [100 100 100] [100 100 100]] 5可以看出对于有:的表达最终的结果外面还嵌套一层list的[],。访问的一定要注意,python最bug的就是,语法灵活,不管怎样写索引语法都是正确的,但是最终的书结果却让你大跌眼镜。
还有array的索引最终产生的是一个一个原始数据的浅拷贝,还和原来的数据共用一块儿内存
产生上面的原因是因为array中直接存放的数据,拷贝的话直接拿走的是pointer,没有取走数据,但是list却会直接发生深拷贝,数据指针全部带走[array([1, 2, 3]), 0, array([100, 100, 100]), array([100, 100, 100])]除了这些之外还有自己的更加牛掰的方式(只能用array)
1)使用布尔数组.感觉甚是强大,就不要自己写什么判断语句啦,注意这种方式得到结果不和原始数组共享空间。布尔索引仅仅适用于数组array,list没资格用。布尔索引最终得到下标索引为true的数据。索引只能是布尔数组
array([16, 32, 48, 64, 80, 16, 32, 48, 64, 80])2)列表索引
列表索引可以是数组和list。返回的数据不和原来的数据共享内存。索引可以是list和array
[0 1 2 3 4 5 6 7 8 9] [1 2 3 4 5] [1 2 3 4 5]array和list区别*2
[ 0 2 4 6 8 10 12 14 16 18] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]array的广播
[[ 0] [10] [20] [30] [40] [50]] [0 1 2 3 4]
[[ 0 1 2 3 4] [10 11 12 13 14] [20 21 22 23 24] [30 31 32 33 34] [40 41 42 43 44] [50 51 52 53 54]]