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

2 Answers2

0

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]
Ramesh
  • 635
  • 2
  • 15
0

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

Vương Hữu Thiện
  • 1,460
  • 14
  • 21