Python中flatten( )函数及函数用法详解

yipeiwu_com5年前Python基础

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]])
>>> 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(矩阵)对象

>>> 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达到同样的效果可以使用列表表达式:

>>> 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()
>>> 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])

总结

以上所述是小编给大家介绍的Python中flatten( )函数及函数用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python中(str,list,tuple)基础知识汇总

python是一门动态解释型的强类型定义语言(先编译后解释) 动态类型语言 动态类型的语言编程时,永远也不用给任何变量指定数据类型,该语言会在你第一次赋值给变量时,在内部将数据类型记录下...

python基础教程之lambda表达式使用方法

Python中,如果函数体是一个单独的return expression语句,开发者可以选择使用特殊的lambda表达式形式替换该函数: 复制代码 代码如下:lambda paramet...

pymysql模块的操作实例

pymysql 模块! pymysql模块时一个第三方模块!需要下载: pymysql的基本使用: import pymysql conn = pymysql.connect(...

Python基于OpenCV实现视频的人脸检测

Python基于OpenCV实现视频的人脸检测

本文实例为大家分享了基于OpenCV实现视频的人脸检测具体代码,供大家参考,具体内容如下 前提条件 1.摄像头 2.已安装Python和OpenCV3 代码 import cv...

Django通过dwebsocket实现websocket的例子

与django推荐的channel不同,dwebsocket使用更加方便简单 使用方法1: 只需views.py文件中,将对应的视图函数添加装饰器 accept_websocket-...