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。

posted @ 2022-03-21 15:45  爱和九九  阅读(1944)  评论(0编辑  收藏  举报