3
$\begingroup$

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?

$\endgroup$
1
  • 1
    $\begingroup$ closely related: 92728, 111863, 56839 $\endgroup$
    – Kuba
    Commented Mar 14, 2017 at 7:39

2 Answers 2

6
$\begingroup$

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.

$\endgroup$
6
$\begingroup$
## & @@ ConstantArray[#2, #] & @@@ L1

Alternatively:

Replace[
 L1,
 sym_Symbol n_. :> Sequence @@ ConstantArray[sym, n],
 {1}
]
$\endgroup$
1
  • $\begingroup$ Thank you. Both answers more or less give the same method. $\endgroup$
    – ferro11001
    Commented Mar 14, 2017 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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