4
$\begingroup$

I'm sure this has been asked before, but I can't find the right combination of search keywords to find it. Apologies.

I want to do a ReplaceAll on a list of lists, for example, I would like:

{{a, b}, {c, d}} /. {i_, j_} -> {i, j, 0}

What I want is to turn this list into {{a,b,0}, {c,d,0}}, but I can't figure out a way to tell Mathematica to only look at lists that are one level "below". Running the above returns {{a, b}, {c, d}, 0}, as i matched {a,b} and j matched {c,d}.

How do I pattern match lists that nested?

$\endgroup$
  • 3
    $\begingroup$ Either use Replace with the correct level specification or narrow your pattern, perhaps by using the contents of the list: {i_Integer, j_Integer} or something like that if possible. I would post an answer, but I'm very positive this is a duplicate... Either way, hope that helped. $\endgroup$ – rm -rf Nov 11 '13 at 0:39
  • 3
    $\begingroup$ Replace is the way to go, but you could also map a ReplaceAll as in #/.{_,_}:>...&/@list. Use :> instead of -> so that it works even when i and j have a value $\endgroup$ – Rojo Nov 11 '13 at 0:42
  • $\begingroup$ You could also use VectorQ[]: list /. v_?VectorQ -> PadRight[v, 1]. $\endgroup$ – J. M. is away May 27 '15 at 23:48
7
$\begingroup$

One way to do this is to build a simple function and then map the function onto the list you want to change:

f[{a_, b_}] := {a, b, 0};
f /@ {{a, b}, {c, d}, {e, f}, {1, 2}}
{{a, b, 0}, {c, d, 0}, {e, f, 0}, {1, 2, 0}}

Or you could use ReplaceRepeated:

{{a, b}, {c, d}, {e, f}, {1, 2}} //. {i_, j_} :> {i, j, 0}
{{a, b, 0}, {c, d, 0}, {e, f, 0}, {1, 2, 0}}
$\endgroup$
5
$\begingroup$

Just for variety (more complex nesting may require modification):

{{a, b}, {c, d}} /. {i_?AtomQ, j_?AtomQ} -> {i, j, 0}

or

Insert[#, 0, -1] & /@ {{a, b}, {c, d}}

or

Append[#, 0] & /@ {{a, b}, {c, d}}
$\endgroup$
2
$\begingroup$

Without the use of rules i mention the following 2 solutions :

PadRight[{{a, b}, {c, d}}, {2, 3}]

Transpose[Append[Transpose[{{a, b}, {c, d}}], {0, 0}]]

I often use such solutions to be able to compile my scripts.

$\endgroup$
1
$\begingroup$

Cases works

lst = {{a, b}, {c, d}};
Cases[lst, {i_, j_} :> {i, j, 0}]

Mathematica graphics

$\endgroup$
-1
$\begingroup$

Similarly,

lst = {{a, b}, {c, d}, {e, f}, {1, 2}}
Map[Append[#, 0] &, lst]

{{a, b, 0}, {c, d, 0}, {e, f, 0}, {1, 2, 0}}
$\endgroup$
  • 1
    $\begingroup$ This is ubpdqn's third solution. For variety, consider PadRight[]. $\endgroup$ – J. M. is away May 27 '15 at 23:46

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.