多个数组合并(拼接)为⼀个数组
Python中多个数组合并为⼀个数组的⽅法整理。
extend
⽅法
该⽅法可以扩展数组,会改变原始数组。
a = [1,2,3,4,7,5,6]
b = [‘a’,’b’]
c = [‘h’,12,’c’]
a.extend(b)
a.extend(c)
print(a)
#
结果:
[1, 2, 3, 4, 7, 5, 6, ‘a’, ‘b’, ‘h’, 12, ‘c’]
直接相加
⽤
+
将各数组连接起来。
a = [1,2,3,4,7,5,6]
b = [‘a’,’b’]
c = [‘h’,12,’c’]
d = a + b +c
print(d)
#
结果:
[1, 2, 3, 4, 7, 5, 6, ‘a’, ‘b’, ‘h’, 12, ‘c’]
flatten
⽅法
flatten()
⽅法是numpy中array数组的⽅法,使⽤时要导⼊包和类型转换。
from numpy import array
a = [1,2,3]
b = [‘a’,’b’,’c’]
c = [‘h’,12,’k’]
e = [a,b,c]
e = array(e)
print(e.flatten())
#
结果:
[‘1’ ‘2’ ‘3’ ‘a’ ‘b’ ‘c’ ‘h’ ’12’ ‘k’]
值得注意的是该⽅法不适⽤各数组中元素个数不同的情况。
a = [1,2,3,4] #
元素个数不同
b = [‘a’,’b’,’c’]
c = [‘h’,12,’k’]
e = [a,b,c]
e = array(e)
print(e.flatten())
#
结果:
[list([1, 2, 3, 4]) list([‘a’, ‘b’, ‘c’]) list([‘h’, 12, ‘k’])]