1. 程式人生 > >numpy中flatten()函式用法

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’.

Returns:

y : ndarray

A copy of the input array, flattened to one dimension.

  

即返回一個摺疊成一維的陣列。但是該函式只能適用於numpy物件,即array或者mat,普通的list列表是不行的。

例子:

1、用於array物件

1

2

3

4

5

6

7

8

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物件

1

2

3

4

>>> a=mat([[1,2,3],[4,5,6]])

>>> a

matrix([[123],

        [456]])<br>>>> a.flatten()<br>matrix([[123456]])<br>

 3、但是該方法不能用於list物件

1

2

3

4

5

6

7

>>> a=[[1,2,3],[4,5,6],['a','b']]

>>> a

[[123], [456], ['a''b']]

>>> a.flatten()                      ###報錯

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

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

 想要list達到同樣的效果可以使用列表表示式:

1

2

>>> [y for in for in x]

[123456'a''b']