say I have a matrix : a = [[1,2,3],[4,5,6],[7,8,9]]
. How can I combine it to b = [1,2,3,4,5,6,7,8,9]
?
Many thanks
say I have a matrix : a = [[1,2,3],[4,5,6],[7,8,9]]
. How can I combine it to b = [1,2,3,4,5,6,7,8,9]
?
Many thanks
Using numpy:
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]
Maybe this is not the most beautiful, but it works:
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [sub_thing for thing in a for sub_thing in thing]
print(b)
Prints:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Without using numpy:
#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
Another way to combine integer matrix could be using the itertools
chain
.
a = [[1,2,3],[4,5,6],[7,8,9]]
list(itertools.chain.from_iterable(a)
prints:
[1, 2, 3, 4, 5, 6, 7, 8, 9]