Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
matrices math problem
#1
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
Reply
#2
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  math problem for experts miltmobley 5 989 Jul-09-2023, 07:14 AM
Last Post: Gribouillis
  4D matrices ali1almakhmari 0 756 Jun-13-2022, 09:21 AM
Last Post: ali1almakhmari
  math.log versus math.log10 stevendaprano 10 2,389 May-23-2022, 08:59 PM
Last Post: jefsummers
  Unable to use Pauli Matrices in QNET Package Rupayan 2 1,904 Sep-25-2021, 06:02 AM
Last Post: Rupayan
  Why getting ValueError : Math domain error in trig. function, math.asin() ? jahuja73 3 3,764 Feb-24-2021, 05:09 PM
Last Post: bowlofred
  Python: Automated Script to Read Multiple Files in Respective Matrices Robotguy 7 4,195 Jul-03-2020, 01:34 AM
Last Post: bowlofred
  Application of dilute matrices chris_drak 0 1,340 Mar-29-2020, 03:04 PM
Last Post: chris_drak
  Partial "visual" Matching of matrices masteripper 15 5,262 Nov-03-2019, 05:41 PM
Last Post: masteripper
  Problem with the math.sin(x) function Carson147 4 2,920 Feb-21-2019, 05:12 PM
Last Post: Carson147
  Flipping matrices problem Qmohankumar0017 10 9,182 Feb-20-2019, 06:47 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020