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。