Re: Re: Replacing Numbers in a List
- To: mathgroup at smc.vnet.net
- Subject: [mg68335] Re: [mg68294] Re: Replacing Numbers in a List
- From: "Carl K. Woll" <carlw at wolfram.com>
- Date: Tue, 1 Aug 2006 07:00:09 -0400 (EDT)
- References: <eahsgh$op1$1@smc.vnet.net> <200607311006.GAA02358@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Paul Abbott wrote: > In article <eahsgh$op1$1 at smc.vnet.net>, > Gregory Lypny <gregory.lypny at videotron.ca> wrote: > >> 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? > > No one has suggested the obvious > > x /. Thread[y -> 222] > > However, this is about twice as slow as Bob Hanlon's suggestion, > > If[MemberQ[y,#],222,#]& /@ x > > Test: > > y={122,211,212,221,223,232,322}; > > x=Table[Random[Integer,{100,325}],{10^5}]; > > Timing[x1 = x /. Thread[y -> 222];] // First > 0.051946 Second > > Timing[x2 = If[MemberQ[y,#],222,#]& /@ x;] // First > 0.037817 Second > > x1 == x2 > True > > Cheers, > Paul > > _______________________________________________________________________ > Paul Abbott Phone: 61 8 6488 2734 > School of Physics, M013 Fax: +61 8 6488 1014 > The University of Western Australia (CRICOS Provider No 00126G) > AUSTRALIA http://physics.uwa.edu.au/~paul Paul, We can use Dispatch to speed up the Thread version: Timing[x1=x/.Dispatch[Thread[y->222]];]//First 0.063 Second Timing[x2=If[MemberQ[y,#],222,#]&/@x;]//First 0.078 Second Carl Woll Wolfram Research