How I can transfer matrix in Python?

Viewed 28
#Example:
A = [[1,2,3,4],[4,3,2,1],[3,2,1,4],[2,1,4,3]]
#How I can transform matrix A become matrix B 
#with matrix B I want to become...
B = [[1],
     [2],
     [3],
     [4],
     [4],
     [3],
     [2],
     [1],
     [3],
     [2],
     [1],
     [4],
     [2],
     [1],
     [4],
     [3]]

And when I save .txt or .csv how I can transfer data without [] in all of the data?

1 Answers

using chain

from itertools import  chain
lst = [[1, 2, 3, 4], [4, 3, 2, 1], [3, 2, 1, 4], [2, 1, 4, 3]]
data = [[x] for xs in lst for x in xs]
result = list(chain.from_iterable(data))
print(data)
print(result)

>>> [[1], [2], [3], [4], [4], [3], [2], [1], [3], [2], [1], [4], [2], [1], [4], [3]]
>>> [1, 2, 3, 4, 4, 3, 2, 1, 3, 2, 1, 4, 2, 1, 4, 3]
Related