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]])>>> aarray([[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]])>>> amatrix([[1, 2, 3], [4, 5, 6]])>>> a.flatten()matrix([[1, 2, 3, 4, 5, 6]])>>> a=mat([[1,2,3],[4,5,6]])>>> amatrix([[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 "<pyshell#10>", line 1, in <module> 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()>>> ymatrix([[1, 3, 2, 4, 3, 5]])>>> y = a.flatten().A>>> yarray([[1, 3, 2, 4, 3, 5]])>>> shape(y)(1, 6)>>> shape(y[0])(6,)>>> y = a.flatten().A[0]>>> yarray([1, 3, 2, 4, 3, 5])
新聞熱點
疑難解答