python中的list是python的内置数据类型,list中的数据类不必相同的,而array的中的类型必须全部相同。在list中的数据类型保存的是数据的存放的地址,简单的说就是指针,并非数据,这样保存一个list就太麻烦了,例如list1=[1,2,3,'a']需要4个指针和四个数据,增加了存储和消耗cpu。
numpy中封装的array有很强大的功能,里面存放的都是相同的数据类型
list1=[1,2,3,'a'] print list1 a=np.array([1,2,3,4,5]) b=np.array([[1,2,3],[4,5,6]]) c=list(a) # array到list的转换 print a,np.shape(a) print b,np.shape(b) print c,np.shape(c)
运行结果:
[1, 2, 3, 'a'] # 元素数据类型不同,并且用逗号隔开 [1 2 3 4 5] (5L,) # 一维数组,类型用tuple表示 [[1 2 3] [4 5 6]] (2L, 3L) [1, 2, 3, 4, 5] (5L,)
创建:
array的创建:参数既可以是list,也可以是元组.使用对应的属性shape直接得到形状
a=np.array((1,2,3,4,5))# 参数是元组 b=np.array([6,7,8,9,0])# 参数是list c=np.array([[1,2,3],[4,5,6]])# 参数二维数组 print a,b, c.shape()
也可以直接改变属性array的形状,-1代表的是自己推算。这里并不是T, reshape(())也可以
c = np.array([[1, 2, 3, 4],[4, 5, 6, 7], [7, 8, 9, 10]]) c.shape # (3L, 4L) c.shape=4,-1 //c.reshape((2,-1)) c <pre style="box-sizing: border-box; overflow: auto; font-size: 14px; padding: 0px; margin-top: 0px; margin-bottom: 0px; line-height: 17.0001px; word-break: break-all; word-wrap: break-word; border: 0px; border-radius: 0px; white-space: pre-wrap; vertical-align: baseline; background-color: rgb(255, 255, 255);">array([[ 1, 2, 3], [ 4, 4, 5], [ 6, 7, 7], [ 8, 9, 10]])
这里的reshape最终相当于是一个浅拷贝,也就是说还是和原来的书c使用相同的内存空间
d=c.reshape((2,-1)) d[1:2]=100 c array([[ 1, 2, 3], [ 4, 4, 5], [100, 100, 100], [100, 100, 100]])
前面在创建数组的时候并没有使用数据类型,这里我们也可以使用数据类型。默认的是int32.
a1=np.array([[1,2,3],[4,5,6]],dtype=np.float64) print a1.dtype,a.dtype #float64 int32<pre style="margin-top: 0px; margin-bottom: 0px; line-height: 17.0001px; box-sizing: border-box; overflow: auto; font-size: 14px; padding: 0px; word-break: break-all; word-wrap: break-word; border: 0px; border-radius: 0px; white-space: pre-wrap; vertical-align: baseline; background-color: rgb(255, 255, 255);">
前面在创建的时候我们都是使用的np.array()
方法从tuple或者list转换成为array,感觉很是费劲,numpy自己提供了很多的方法让我们自己直接创建一个array.
新闻热点
疑难解答