Re: Replacing Numbers in a List
- To: mathgroup at smc.vnet.net
- Subject: [mg68294] Re: Replacing Numbers in a List
- From: Paul Abbott <paul at physics.uwa.edu.au>
- Date: Mon, 31 Jul 2006 06:06:21 -0400 (EDT)
- Organization: The University of Western Australia
- References: <eahsgh$op1$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
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