关于numpy:python,如何将整数矩阵组合到列表中

Python, how to combine integer matrix to a list

假设我有一个矩阵:a = [[1,2,3],[4,5,6],[7,8,9]]。我怎样才能把它和b = [1,2,3,4,5,6,7,8,9]结合起来?

多谢


使用NUMPY:

1
2
3
4
5
import numpy
a = [[1,2,3],[4,5,6],[7,8,9]]
b = numpy.hstack(a)
list(b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]


使用NUMPY:

list(np.array(a).flatten())


另一种组合整数矩阵的方法是使用itertoolschain

1
2
a = [[1,2,3],[4,5,6],[7,8,9]]
list(itertools.chain.from_iterable(a)

印刷品:

[1, 2, 3, 4, 5, 6, 7, 8, 9]


不使用numpy:

1
2
3
4
5
#make the empty list b
b=[]
for row in a:#go trough the matrix a
    for value in row: #for every value
        b.append(value) #python is fun and easy


也许这不是最漂亮的,但它很管用:

1
2
3
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [sub_thing for thing in a for sub_thing in thing]
print(b)

印刷品:

[1, 2, 3, 4, 5, 6, 7, 8, 9]