一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python中flatten( )函数及函数用法详解

时间:2018-11-08 编辑:猪哥 来源:一聚教程网

flatten()函数用法

flatten是numpy.ndarray.flatten的一个函数,即返回一个一维数组。

flatten只能适用于numpy对象,即array或者mat,普通的list列表不适用!。

a.flatten():a是个数组,a.flatten()就是把a降到一维,默认是按行的方向降 。
a.flatten().A:a是个矩阵,降维后还是个矩阵,矩阵.A(等效于矩阵.getA())变成了数组。具体看下面的例子:

1、用于array(数组)对象

>>> 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(矩阵)对象

>>> 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达到同样的效果可以使用列表表达式:

>>> 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用法

一、用在数组

>>> a = [[1,3],[2,4],[3,5]]
>>> a = array(a)
>>> a.flatten()
array([1, 3, 2, 4, 3, 5])

二、用在列表

如果直接用flatten函数会出错

>>> 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'

正确的用法

>>> 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']

或者(不理解)

>>> 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']

三、用在矩阵

>>> 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])

热门栏目