numpy庫數組拼接np.concatenate()函數的非常規用法(只傳入一個list參數)


concatenate([a1, a2, …], axis=0)

這是numpy里一個非常方便的數組拼接函數,也就是說,傳入n個數組在中括號中,即可得到一個這些數組拼接好的新的大數組;axis=0表示從行方向上拼接,=1表示從列方向上拼接,如果是高維以此類推。

但是,今天遇到一個新的用法,如example 1:

# example 1
listt = [[1,2,3,4,5,6],
        [1,2,3,4,5,6],
        [6,7,4,3,3,5],
        [7,9,4,3,32,4]]
listtt = [[1,2,3,4,5,6],
        [1,2,3,4,5,6],
        [6,7,4,3,3,5],
        [7,9,4,3,32,4]]
listttt = [[1,2,3,4,5,6],
        [1,2,3,4,5,6],
        [6,7,4,3,3,5],
        [7,9,4,3,32,4]]
list=[]
list.append(np.concatenate([listt],0))
list.append(np.concatenate([listtt],0))
list.append(np.concatenate([listttt],0))
print(list)
list1=np.concatenate(list,0)
print(list1)
print(list.__class__,"-----",list.__class__)

這段代碼的運行結果為:

[array([[ 1,  2,  3,  4,  5,  6],
       [ 1,  2,  3,  4,  5,  6],
       [ 6,  7,  4,  3,  3,  5],
       [ 7,  9,  4,  3, 32,  4]]), array([[ 1,  2,  3,  4,  5,  6],
       [ 1,  2,  3,  4,  5,  6],
       [ 6,  7,  4,  3,  3,  5],
       [ 7,  9,  4,  3, 32,  4]]), array([[ 1,  2,  3,  4,  5,  6],
       [ 1,  2,  3,  4,  5,  6],
       [ 6,  7,  4,  3,  3,  5],
       [ 7,  9,  4,  3, 32,  4]])]
[[ 1  2  3  4  5  6]
 [ 1  2  3  4  5  6]
 [ 6  7  4  3  3  5]
 [ 7  9  4  3 32  4]
 [ 1  2  3  4  5  6]
 [ 1  2  3  4  5  6]
 [ 6  7  4  3  3  5]
 [ 7  9  4  3 32  4]
 [ 1  2  3  4  5  6]
 [ 1  2  3  4  5  6]
 [ 6  7  4  3  3  5]
 [ 7  9  4  3 32  4]]
<class 'list'> ----- <class 'list'>

Process finished with exit code 0

可以看到,list是一個數組的數組,但是傳入的參數還是0,所以還是從0維重合,把第三維度(array)壓縮成了二維。

但是,如果是小括號呢?

# example 1-改
listt = [[1,2,3,4,5,6],
        [1,2,3,4,5,6],
        [6,7,4,3,3,5],
        [7,9,4,3,32,4]]
listtt = [[1,2,3,4,5,6],
        [1,2,3,4,5,6],
        [6,7,4,3,3,5],
        [7,9,4,3,32,4]]
listttt = [[1,2,3,4,5,6],
        [1,2,3,4,5,6],
        [6,7,4,3,3,5],
        [7,9,4,3,32,4]]
list=[]
# 把下面的中括號變成了小括號 list.append(np.concatenate((listt),
0)) list.append(np.concatenate((listtt),0)) list.append(np.concatenate((listttt),0)) print(list) list1=np.concatenate(list,0) print(list1) print(list.__class__,"-----",list.__class__)

結果:

[array([ 1,  2,  3,  4,  5,  6,  1,  2,  3,  4,  5,  6,  6,  7,  4,  3,  3,
        5,  7,  9,  4,  3, 32,  4]), array([ 1,  2,  3,  4,  5,  6,  1,  2,  3,  4,  5,  6,  6,  7,  4,  3,  3,
        5,  7,  9,  4,  3, 32,  4]), array([ 1,  2,  3,  4,  5,  6,  1,  2,  3,  4,  5,  6,  6,  7,  4,  3,  3,
        5,  7,  9,  4,  3, 32,  4])]
[ 1  2  3  4  5  6  1  2  3  4  5  6  6  7  4  3  3  5  7  9  4  3 32  4
  1  2  3  4  5  6  1  2  3  4  5  6  6  7  4  3  3  5  7  9  4  3 32  4
  1  2  3  4  5  6  1  2  3  4  5  6  6  7  4  3  3  5  7  9  4  3 32  4]
<class 'list'> ----- <class 'list'>

Process finished with exit code 0

也就是說,加小括號,會把內容拉成一維,我不知道是故意為之還是開發這個API的時候的巧合,在網上好像沒找到這種用法,可能只是一種BUG?whatever。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM