0
$\begingroup$

I wonder how to replace specific element (even though repeated) within sublists of a nested list with multiple elements while maintaining the list structure. Suppose the following:

{{{{O1, 2, 22, 24, 6, PoP1, 5, 23, 27, 17, PoP2, 18, 28, 14, D1}, {O1,
     1, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 13, D1}, {O1, 2,
     22, 24, 6, PoP1, 5, 23, 27, 17, PoP2, 18, 28, 14, 13, D1}, {O1, 
    2, 22, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 13, D1}, {O1,
     2, 1, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 13, D1}, {O1,
     1, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 13, 14, 
    D1}, {O1, 1, 21, 22, 24, 6, PoP1, 5, 23, 27, 17, PoP2, 18, 28, 14,
     D1}, {O1, 1, 2, 22, 24, 6, PoP1, 5, 23, 27, 17, PoP2, 18, 28, 14,
     D1}, {O1, 2, 22, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 
    13, 14, D1}, {O1, 2, 1, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 
    27, 13, 14, D1}, {O1, 2, 1, 21, 22, 24, 6, PoP1, 5, 23, 27, 17, 
    PoP2, 18, 28, 14, D1}, {O1, 1, 21, 22, 24, 6, PoP1, 5, 23, 27, 17,
     PoP2, 18, 28, 14, 13, D1}, {O1, 1, 2, 22, 24, 6, PoP1, 5, 23, 27,
     17, PoP2, 18, 28, 14, 13, D1}, {O1, 1, 2, 22, 21, 23, 5, PoP1, 6,
     24, 28, 18, PoP2, 17, 27, 13, D1}, {O1, 2, 1, 21, 22, 24, 6, 
    PoP1, 5, 23, 27, 17, PoP2, 18, 28, 14, 13, D1}, {O1, 1, 2, 22, 21,
     23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 13, 14, D1}}}}

I would like to substitute PoP1 with XXX,YYY,ZZZ and PoP2 with SSS,FFF while having the same list depth and sublists. I have tried with /. but it introduces a new sublist like :

{{{{O1, 2, 22, 24, 6, {XXX, YYY, ZZZ}, 5, 23, 27, 17, {SSS, FFF},
     18, 28, 14, D1}, {O1,...
$\endgroup$
  • $\begingroup$ Have a look at Sequence. $\endgroup$ – b.gates.you.know.what Nov 8 '18 at 16:39
  • $\begingroup$ You were right, just use sequence and is done. Thanks! $\endgroup$ – Besi Nov 8 '18 at 16:47
0
$\begingroup$

Below is a minimal working example that you can adapt to your needs:

{{"x",1,3},{2,4,"z"}}/.{"x"->Sequence@@{"a","b"},"z"->Sequence@@{"c","d"}}

produces:

{{"a", "b", 1, 3}, {2, 4, "c", "d"}}

$\endgroup$
0
$\begingroup$

making use of /. with element->Sequence[element1,element2] actually does it.

$\endgroup$

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.