numpy下的flatten()函数⽤法
flatten是numpy.ndarray.flatten的⼀个函数,其官⽅⽂档是这样描述的:
numpy库统计函数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’.
Returns:y : ndarray
A copy of the input array, flattened to one dimension.
即返回⼀个折叠成⼀维的数组。但是该函数只能适⽤于numpy对象,即array或者mat,普通的list列表是不⾏的。
例⼦:
1、⽤于array对象
from numpy import *
>>>a=array([[1,2],[3,4],[5,6]])  ###此时a是⼀个array对象
>>>a
array([[1,2],[3,4],[5,6]])
>>>a.flatten()
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]])
3、但是该⽅法不能⽤于list对象
>>> a=[[1,2,3],[4,5,6],['a','b']]
>>> a
[[1, 2, 3], [4, 5, 6], ['a', 'b']]
>>> a.flatten()                      ###报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'flatten'
想要list达到同样的效果可以使⽤列表表达式:
>>> [y for x in a for y in x]
[1, 2, 3, 4, 5, 6, 'a', 'b']