欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中flatten()函數(shù)用法詳解

 更新時(shí)間:2023年02月16日 08:23:17   作者:篤℃  
本文主要介紹了python中flatten()函數(shù)用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1. 函數(shù)介紹

flatten是numpy.ndarray.flatten的一個(gè)函數(shù),即返回一個(gè)一維數(shù)組。常用如下:

  • a.flatten():a是個(gè)數(shù)組,a.flatten()就是把a(bǔ)降到一維,默認(rèn)是按行的方向降 。
  • m.flatten():m是個(gè)矩陣,降維后還是個(gè)矩陣,m.A(等效于矩陣.getA())才變成了數(shù)組。

2. 示例代碼

2.1 數(shù)組(array).flatten()

>>> a = [[1,3],[2,4],[3,5]]
>>> a = array(a)
>>> a.flatten()
array([1, 3, 2, 4, 3, 5])

2.2 矩陣(mat).flatten()

>>> a = [[1,3],[2,4],[3,5]]
>>> a = mat(a)
>>> y = a.flatten()
>>> y
matrix([[1, 3, 2, 4, 3, 5]])    ## 經(jīng)過降維仍為矩陣類型
>>> y = a.flatten().A
>>> y
array([[1, 3, 2, 4, 3, 5]])        ## 此時(shí)變?yōu)閿?shù)組類型
>>> shape(y)
(1, 6)
>>> shape(y[0])
(6,)
>>> y = a.flatten().A[0]
>>> y
array([1, 3, 2, 4, 3, 5])

2.3 列表(list).flatten()

直接使用list.flatten()會(huì)出錯(cuò)。

>>> a = [[1,3],[2,4],["abc","def"]]
>>> a.flatten()

# 報(bào)錯(cuò)
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],["abc","def"]]
>>> a1 = [y for x in a for y in x]
>>> a1
[1, 3, 2, 4, 'abc', 'def']

3. 參考

【1】https://blog.csdn.net/qq_41542989/article/details/109050472

到此這篇關(guān)于python中flatten()函數(shù)用法詳解的文章就介紹到這了,更多相關(guān)python flatten() 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論