Python, how to combine integer matrix to a list
假设我有一个矩阵:
多谢
使用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:
另一种组合整数矩阵的方法是使用
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]