I have the following list of lists:
l = {{5,6,0,8,5,9}, {8,4,4,3,5,8}, {9,4,3,2,5,7}}
now if there is a 0 in one of the lists Mathematica should replace the last element in the list with 0 like this:
l1 = {{5,6,0,8,5,0}, {8,4,4,3,5,8}, {9,4,3,2,5,7}}
the l1
should be my output. I have no idea how is can do this, I hope someone can help.
l /. x_ /; MemberQ[x, 0] :> ReplacePart[x, -1 -> 0]
$\endgroup$l1 = l /. a: {___, 0, ___ } :> ReplacePart[a, -1 -> 0]
$\endgroup$l1 /. {a___, 0, b___, _} -> {a, 0, b, 0}
. I see no reason forRuleDelayed
either? $\endgroup$RuleDelayed
is standard if you are using variables in both sides ofRule
; it prevents naming conflicts, etc. For instance,a = 3; {1, 2, 3} /. a_Integer -> a
does not work. One could clear variables prior to runningReplaceAll
, but writingClear
every time there is/.
is too inconvenient! $\endgroup$