1
$\begingroup$

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}}*)
$\endgroup$
2
$\begingroup$
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.} *)
$\endgroup$
  • $\begingroup$ Great! But suppose that I change the replacement list from {k1p,k2p} to {km1,k2p,km2}. How could I alter the above to automatically act on the new replacement list of arbitrary length? $\endgroup$ – tarhawk Mar 7 '15 at 20:30
  • $\begingroup$ @tarhawk, please see the update. $\endgroup$ – kglr Mar 7 '15 at 20:33

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.