How I can transfer matrix in Python?

Question:

#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?

Asked By: Công Minh Đặng

||

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]
Answered By: Ramesh

Write full

A = [[1,2,3,4],[4,3,2,1],[3,2,1,4],[2,1,4,3]]
B = []

for Am in A:
  for x in Am:
    B.append([x])

print (B)

Write short

A = [[1,2,3,4],[4,3,2,1],[3,2,1,4],[2,1,4,3]]
B = [[x] for Am in A for x in Am]
print (B)

Link Example

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.