flatten()函數用法
flatten是numpy.ndarray.flatten的一個函數,即返回一個一維數組。
flatten只能適用於numpy對象,即array或者mat,普通的list列表不適用!。
a.flatten():a是個數組,a.flatten()就是把a降到一維,默認是按行的方向降 。
a.flatten().A:a是個矩陣,降維后還是個矩陣,矩陣.A(等效於矩陣.getA())變成了數組。具體看下面的例子:
1、用於array(數組)對象
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>>
from
numpy
import
*
>>> a
=
array([[
1
,
2
],[
3
,
4
],[
5
,
6
]])
>>> a
array([[
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(矩陣)對象
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
>>> 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
]])
>>> 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
]])
>>> 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達到同樣的效果可以使用列表表達式:
|
1
2
3
4
5
|
>>> 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用法
一、用在數組
|
1
2
3
4
|
>>> a
=
[[
1
,
3
],[
2
,
4
],[
3
,
5
]]
>>> a
=
array(a)
>>> a.flatten()
array([
1
,
3
,
2
,
4
,
3
,
5
])
|
二、用在列表
如果直接用flatten函數會出錯
|
1
2
3
4
5
6
7
|
>>> 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'
|
正確的用法
|
1
2
3
4
|
>>> 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'
]
|
或者(不理解)
|
1
2
3
4
|
>>> 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'
]
|
三、用在矩陣
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
>>> a
=
[[
1
,
3
],[
2
,
4
],[
3
,
5
]]
>>> a
=
mat(a)
>>> y
=
a.flatten()
>>> y
matrix([[
1
,
3
,
2
,
4
,
3
,
5
]])
>>> y
=
a.flatten().A
>>> y
array([[
1
,
3
,
2
,
4
,
3
,
5
]])
>>> shape(y)
(
1
,
6
)
>>> shape(y[
0
])
(
6
,)
>>> y
=
a.flatten().A[
0
]
>>> y
array([
1
,
3
,
2
,
4
,
3
,
5
])
|

