2
$\begingroup$

I'm trying to replace the second element within a list of ordered pairs depending on whether that ordered pair exists within another set.

shortlist = Flatten[Table[{i, j}, {i, 0, 3}, {j, 1, 2}], 1]
sublist = {{0, 2}, {1, 1}, {2, 1}}

I want to do something like this

shortlist //. x_ /; !MemberQ[sublist, x] -> {x[[1]], 0}

where the result is

{{0,0},{0,2},{1,1},{1,0},{2,1},{3,0},{3,0}}

where the 'x' components of the list remained the same, but those that were not members of the sublist had their 'y' components changed to zero.

$\endgroup$
2
  • 5
    $\begingroup$ I think you're almost there; the problem is that you're using -> instead of :>, so x is treated as a symbol and not bound by the lhs. But even if you fix that /. would attempt the rule on every part of the expression, even ones like the whole list itself, which also match the pattern. Use a more specific pattern: shortlist /. {x_, y_} /; !MemberQ[sublist, {x,y}] :> {x,0} If you have nesting issues, and want to make sure to only do the replacement on e.g. the first level, use Replace with a level specification: Replace[shortlist, {x_, y_} /; !MemberQ[sublist, {x,y}] :> {x,0}, {1}] $\endgroup$
    – thorimur
    Sep 15 '21 at 1:09
  • $\begingroup$ My hero, thank you so much. I always have issues with these kinds of symbolic heavy functions in Mathematica. I really appreciate the detailed explanation. $\endgroup$
    – tquarton
    Sep 15 '21 at 1:23