I am using pattern matching to identify elements in a list to be replaced. How can I supply a list of patterns to match and replace all elements in the list that match the pattern? The problem I have now is that each replacement generates a new list. But what I want is a single list with all pattern matched elements replaced. Thus far I have tried,
x={k1p->0.214161,km1->35.8125,k2p->0.3880,km2->39.57}/.
PatternSequence[#->_]->#>0.0&/@{k1p,k2p}
(*{{k1p->0.,km1->35.8125,k2p->0.388,km2->39.57},{k1p->0.214161,km1->35.8125,k2p->0.388,km2->0.}}*)
And I've tried to use replace repeated (//.) Which does give a single list, however nothing is replaced.
x={k1p->0.214161,km1->35.8125,k2p->0.3880,km2->39.57}//.PatternSequence[#->_]->#->0.0&/@{{k1p,km2}}
(*{{k1p->0.214161,km1->35.8125,k2p->0.388,km2->39.57}}*)
Answer
expr = {k1p -> 0.214161, km1 -> 35.8125, k2p -> 0.3880, km2 -> 39.57};
expr /. PatternSequence[p : k1p | k2p -> _] -> (p -> 0.0)
(* or expr /. Rule[p:k1p|k2p,_] :> Rule[p,0.0] *)
(* {k1p -> 0., km1 -> 35.8125, k2p -> 0., km2 -> 39.57} *)
More generally,
lst = {km1, k2p, km2};
exprs /. Rule[p : Alternatives @@ lst, _] :> Rule[p, 0.0]
(* {k1p -> 0.214161, km1 -> 0., k2p -> 0., km2 -> 0.} *)
Comments
Post a Comment