Re: Replacing Numbers in a List
- To: mathgroup at smc.vnet.net
- Subject: [mg68262] Re: Replacing Numbers in a List
- From: Peter Pein <petsie at dordos.net>
- Date: Mon, 31 Jul 2006 03:45:15 -0400 (EDT)
- References: <eahsgh$op1$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Gregory Lypny schrieb: > Hello everyone, > > 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? > > Regards, > > Gregory > ReplaceAll and Alternatives come to mind: In[1]:= x1 = x2 = (Fold[10*#1 + #2 & , 0, #1] & ) /@ Table[Random[Integer, {1, 3}], {10^6}, {3}]; y = {122, 211, 212, 221, 223, 232, 322}; Timing[Do[x1 = ReplacePart[x1, 222, Position[x1, y[[i]]]], {i, Length[y]}]; ] Out[3]= {1.264079*Second, Null} In[4]:= Timing[x2 = x2 /. Alternatives @@ y -> 222; ] Out[4]= {0.4880301*Second, Null} In[5]:= x2 === x1 Out[5]= True Peter