Python中flatten( )函数及函数用法详解 |
您所在的位置:网站首页 › pythonarray函数用法 › Python中flatten( )函数及函数用法详解 |
flatten()函数用法 flatten是numpy.ndarray.flatten的一个函数,即返回一个一维数组。 flatten只能适用于numpy对象,即array或者mat,普通的list列表不适用!。 a.flatten():a是个数组,a.flatten()就是把a降到一维,默认是按行的方向降 。a.flatten().A:a是个矩阵,降维后还是个矩阵,矩阵.A(等效于矩阵.getA())变成了数组。具体看下面的例子: 1、用于array(数组)对象 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 >>> from numpy import * >>> a=array([[1,2],[3,4],[5,6]]) >>> a array([[1, 2], [3, 4], [5, 6]]) >>> a.flatten() #默认按行的方向降维 array([1, 2, 3, 4, 5, 6]) >>> a.flatten('F') #按列降维 array([1, 3, 5, 2, 4, 6]) >>> a.flatten('A') #按行降维 array([1, 2, 3, 4, 5, 6]) >>>2、用于mat(矩阵)对象 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 >>> a=mat([[1,2,3],[4,5,6]]) >>> a matrix([[1, 2, 3], [4, 5, 6]]) >>> a.flatten() matrix([[1, 2, 3, 4, 5, 6]]) >>> a=mat([[1,2,3],[4,5,6]]) >>> a matrix([[1, 2, 3], [4, 5, 6]]) >>> a.flatten() matrix([[1, 2, 3, 4, 5, 6]]) >>> y=a.flatten().A >>> shape(y) (1L, 6L) >>> shape(y[0]) (6L,) >>> a.flatten().A[0] array([1, 2, 3, 4, 5, 6]) >>>从中可以看出matrix.A的用法和矩阵发生的变化。 3、但是该方法不能用于list对象,想要list达到同样的效果可以使用列表表达式: ? 1 2 3 4 5 >>> a=array([[1,2],[3,4],[5,6]]) >>> [y for x in a for y in x] [1, 2, 3, 4, 5, 6] >>> !下面看下Python中flatten用法 一、用在数组 ? 1 2 3 4 >>> a = [[1,3],[2,4],[3,5]] >>> a = array(a) >>> a.flatten() array([1, 3, 2, 4, 3, 5])二、用在列表 如果直接用flatten函数会出错 ? 1 2 3 4 5 6 7 >>> a = [[1,3],[2,4],[3,5]] >>> a.flatten() Traceback (most recent call last): File "", line 1, in a.flatten() AttributeError: 'list' object has no attribute 'flatten'正确的用法 ? 1 2 3 4 >>> a = [[1,3],[2,4],[3,5],["abc","def"]] >>> a1 = [y for x in a for y in x] >>> a1 [1, 3, 2, 4, 3, 5, 'abc', 'def']或者(不理解) ? 1 2 3 4 >>> a = [[1,3],[2,4],[3,5],["abc","def"]] >>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x] >>> flatten(a) [1, 3, 2, 4, 3, 5, 'abc', 'def']三、用在矩阵 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 >>> a = [[1,3],[2,4],[3,5]] >>> a = mat(a) >>> y = a.flatten() >>> y matrix([[1, 3, 2, 4, 3, 5]]) >>> y = a.flatten().A >>> y array([[1, 3, 2, 4, 3, 5]]) >>> shape(y) (1, 6) >>> shape(y[0]) (6,) >>> y = a.flatten().A[0] >>> y array([1, 3, 2, 4, 3, 5]) 2017年老男孩全栈python第2期视频教程![]() ![]() ![]() ![]() ![]() ![]() |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |