# python numpy库中flatten()函数用法

flatten是numpy.ndarray.flatten的一个函数，其官方文档：

ndarray.flatten(order='C')

Return a copy of the array collapsed into one dimension.

 Parameters: 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’. y : ndarray A copy of the input array, flattened to one dimension.

1.用于array：

>>> import numpy as np
>>> alist = [[1,2,3],[5,6,7],[8,9,10]]
>>> ar1 = np.array(alist)  #二维数组 m * n 形式
>>> ar1
array([[ 1,  2,  3],
[ 5,  6,  7],
[ 8,  9, 10]])
>>> ar1.flatten()

array([ 1,  2,  3,  5,  6,  7,  8,  9, 10])  #一维数组 1 * n 形式

2.用于矩阵：

>>> ma = np.mat(alist)  #二维矩阵 m * n 形式
>>> ma
matrix([[ 1,  2,  3],
[ 5,  6,  7],
[ 8,  9, 10]])
>>> ma1 = ma.flatten()  #二维数组，1 * n 形式
>>> ma1

matrix([[ 1,  2,  3,  5,  6,  7,  8,  9, 10]])

>>> ma2 = ma.flatten().A #二维数组
>>> ma2

array([[ 1,  2,  3,  5,  6,  7,  8,  9, 10]])

>>> ma3 = ma.flatten().A[0] #一维数组
>>> ma3

array([ 1,  2,  3,  5,  6,  7,  8,  9, 10])

matrix.A  中的 A ：array

matrix.A[0] :取二维数组中第一行元素

3.用于列表：

>>> alist.flatten() #直接使用，出错
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
alist.flatten()

AttributeError: 'list' object has no attribute 'flatten'

>>> [y for x in alist for y in x]
[1, 2, 3, 5, 6, 7, 8, 9, 10]