Suppose I have a list like
L1 = {a,2b,3c,...}
I want to transform it to a list of the form
L2 = {a, b, b, c, c, c, ...}
How do I do that?
So our L1
is actually a list of things with format Times[__]
:
In[88]:= L1 = Range[26]*ToExpression@Alphabet[]
Out[88]= {a, 2 b, 3 c, 4 d, 5 e, 6 f, 7 g, 8 h, 9 i, 10 j, 11 k, 12 l,
13 m, 14 n, 15 o, 16 p, 17 q, 18 r, 19 s, 20 t, 21 u, 22 v, 23 w,
24 x, 25 y, 26 z}
In[97]:= L1[[13]] // FullForm
Out[97]:= Times[13,m]
Which means we can use this in ReplaceAll
:
L1 /. Times[n_Integer, s_] :> ConstantArray[s, n] // Flatten
The Flatten
call there simply takes the nested lists and flattens them all out.
## & @@ ConstantArray[#2, #] & @@@ L1
Alternatively:
Replace[
L1,
sym_Symbol n_. :> Sequence @@ ConstantArray[sym, n],
{1}
]