python中的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对象

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对象

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

3、但是该方法不能用于list对象

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

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

>>> a.flatten() ###报错

traceback (most recent call last):

file "", line 1, in

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

想要list达到同样的效果可以使用列表表达式:

>>> [y for x in a for y in x]

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

4、用在矩阵

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值