# Python中flatten( ),matrix.A用法

### flatten()函数用法

flatten是numpy.ndarray.flatten的一个函数，即返回一个折叠成一维的数组。但是该函数只能适用于numpy对象，即array或者mat，普通的list列表是不行的。

Parameters:

ndarray.flatten(order='C')
Return a copy of the array collapsed into one dimension.
order : {‘C’, ‘F’, ‘A’, ‘K’}, optional

‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran- style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.

a是个矩阵或者数组，a.flatten()就是把a降到一维，默认是按横的方向降

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

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