I have a series of lists in the form below:
list={ {1,1} , {2,2}, {3,{3,1},{3,2},{31,{31,1},{32,2}}} }
Its a nested list which the dimension is changing case to case. I want to manipulate the list to have an output like this:
LIST={{1,1},{2,2},{3,3,1},{3,3,2},{3,31,31,1},{3,31,32,2}}
I am trying to use this ReplaceList rule
list //. {a_, {b___}} :> {a, b}
But it is not working at all!! How should I make a list out of this nested list?
Answer
The problem: your pattern, {a_, {b___}}
will only match a list with exactly two elements, the second of which has to be a list. As you can see, there is no such list anywhere in your expression, which is why it doesn't work.
You can correct it as follows:
sol = list //. {h__Integer, t__List} :> Map[{h} ~Join~ # &, {t}]
(* {{1, 1}, {2, 2}, {{3, 3, 1}, {3, 3, 2}, {{3, 31, 31, 1}, {3, 31, 32, 2}}}} *)
Note that the lists have the correct elements, but are nested. You can again employ rules to "flatten" them out with:
FixedPoint[Replace[#, {x__List} :> x, {1, Infinity}] &, sol]
(* {{1, 1}, {2, 2}, {3, 3, 1}, {3, 3, 2}, {3, 31, 31, 1}, {3, 31, 32, 2}} *)
Comments
Post a Comment