![]() |
matrices math problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: matrices math problem (/thread-12496.html) |
matrices math problem - lokoprof - Aug-27-2018 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 RE: matrices math problem - perfringo - Aug-27-2018 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 |