3
$\begingroup$

let's say I have a list of lists that looks like

    abc={{1,{{1},{2}}},{2,{{3},{4},{5}}},{3,{{2}}}}//TableForm, 

where the first entry in every row, the one without brackets, is the x-value and the second entries are the corresponding y-values.

While my x-value is always one entry, the amount of y-values do vary in a non consistant manner.

I want Mathematica to take every signle x-value and "duplicate" it corresponding to the amount of y-values attached, so I will get a list of coordinates with one x- and one y-value each, like:

    abcnew={{1,1},{1,2},{2,3},{2,4},{2,5},{3,2}}//TableForm

Is there a fast and easy way to do this in Mathematica 4.0 with list-manipulation or do I have to combine Count with Padding?

Thank you for your help!

$\endgroup$
4
$\begingroup$
abcnew  = Join @@ (Thread[{#, Join @@ #2}] & @@@ abc) (* or *)
abcnew = Join @@ (Thread[{#[[1]], Flatten[#[[2]]]}] & /@ abc)

{{1, 1}, {1, 2}, {2, 3}, {2, 4}, {2, 5}, {3, 2}}

$\endgroup$
2
  • $\begingroup$ Awesome, this does the job in the way I needed! Thank you! $\endgroup$ – Andy Feb 16 '18 at 9:45
  • $\begingroup$ @Andy, my pleasure. Thank you for the accept. $\endgroup$ – kglr Feb 16 '18 at 10:01
1
$\begingroup$

Please try the following:

abcnew = Map[Function[Reverse[#]], 
Partition[Flatten[Map[Function[Thread[List[#[[2]], #[[1]]]]],
    Map[Function[
            List[#[[1]],
            Flatten[#[[2]]]]
        ],
  abc]]], 2]]

You can replace #[[1]] with First[#] and #[[2]] with Last[#]. So it would read:

abcnew = Map[Function[Reverse[#]], Partition[Flatten[Map[Function[Thread[List[Last[#], First[#]]]],
    Map[Function[
            List[First[#],
            Flatten[Last[#]]]
        ],
  abc]]], 2]]

All the function are pre version 4.0. I no longer have that version installed so could not test on that version as some of these function have been updated post version 4. This should not work if attempt to extend past X,Y to something like X,Y,Z; note the use of Partition[data,2].

$\endgroup$
1
  • $\begingroup$ Both of this do work, thank you for your help! However, I chose kglr's answer since it's shorter and easier for me to modify for similar constructed lists, sorry. $\endgroup$ – Andy Feb 16 '18 at 9:51
1
$\begingroup$

How about:

Flatten[abc /. {x_Integer, {y : _List ...}} :> Thread[{x, Join@y}], 1]

(* {{{1, 1}, {1, 2}}, {{2, 3}, {2, 4}, {2, 5}}, {{3, 2}}} *)
$\endgroup$
1
  • $\begingroup$ This one also works, thank you! $\endgroup$ – Andy Feb 16 '18 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.