MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Replacing Numbers in a List

  • To: mathgroup at smc.vnet.net
  • Subject: [mg68289] Re: Replacing Numbers in a List
  • From: albert <awnl at arcor.de>
  • Date: Mon, 31 Jul 2006 04:33:41 -0400 (EDT)
  • References: <eahsgh$op1$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Hi Gregory,

> I have a long list of integers called x, and I want to replace those
> that are members of list y with the number 222.
> 
> I did it this way with a Do loop.
> 
> y = {122, 211, 212, 221, 223, 232, 322};
> Do[x = ReplacePart[x,222, Position[x, y[[i]]]],{i, Length@y} ]
> 
> Is this OK, or is there a more direct way?

Since it does what you want, it is ok :-). I don't know whether the
following qualify to be more direct, but for me they are easier to
correlate with the description of your problem:

x = Map[If[MemberQ[y,#],222,#]&,x]

x = Replace[x,Alternatives@@y -> 222 ,{1}]

they both also have the advantage, that they don't make Length[y] copies of
x, so they both should be more memory efficient. Concerning runtime I don't
know, you would have to try that out. If efficiency is a matter, there
might be better methods, but those would probably not be 'more direct'.

hth,

albert


  • Prev by Date: RE: Replacing Numbers in a List
  • Next by Date: Using implicit information about row indices
  • Previous by thread: RE: Replacing Numbers in a List
  • Next by thread: Re: Replacing Numbers in a List