numpy下的flatten()函數用法

即返回一個摺疊成一維的數組。但是該函數只能適用於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']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章