Python Forum

Full Version: matrices math problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have this problem I want to solve in python but I am very new to the language. Pls help out.
I have a N x M dimensional data I want to convert to one row. i have tried to append to but not working

for example:

x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
x..n y..n z..n

I want this data to be in form of :

x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y4 z4 x..n y..n z..n

pls help out. Thanks
I assume that you want flatten matrix (list of lists) into list.

1. Simple nested for-loop with append:

>>> m = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
...     ]
>>> f = []
>>> for x in m:
...    for y in x:
...        f.append(y)
...
>>> f
[1, 2, 3, 4, 5 ,6 ,7 ,8, 9]
2. List comprehension

>>> m = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
...     ]
>>> [y for x in m for y in x]
[1, 2, 3, 4, 5 ,6 ,7 ,8, 9]
3. Using sum

>>> m = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
...     ]
>>> sum(m, [])
[1, 2, 3, 4, 5 ,6 ,7 ,8, 9]
4. Using itertools

>>> import itertools
>>> m = [
...     [1, 2, 3],
...     [4, 5, 6],
...     [7, 8, 9],
...     ]
>>> list(itertools.chain(*m))
[1, 2, 3, 4, 5 ,6 ,7 ,8, 9]
etc, etc, etc