python 中列表(list)合并、数组(array)合并

时间:2021-10-22 03:35:20

列表合并

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

(1)

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

(2)

>>> a.extend(b)
>>> a
[[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]]

数组合并

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,5,6]])
>>> b = np.array([[1,1,1],[2,2,2]]

数组纵向合并:
方法(1)

>>> c = np.vstack((a,b))
>>> c
array([[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]])

方法(2)

>>> c = np.r_[a,b]
>>> c
array([[1, 2, 3], [4, 5, 6], [1, 1, 1], [2, 2, 2]])

数组横向合并:
方法(1)

>>> d = np.hstack((a,b))
>>> d
array([[1, 2, 3, 1, 1, 1], [4, 5, 6, 2, 2, 2]])

方法(2)

>>> d = np.c_[a,b]
>>> d
array([[1, 2, 3, 1, 1, 1], [4, 5, 6, 2, 2, 2]])