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