MathGroup Archive 2008

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

Search the Archive

Fast way to select those elements from a list that are in another

  • To: mathgroup at smc.vnet.net
  • Subject: [mg86740] Fast way to select those elements from a list that are in another
  • From: Andrew Moylan <andrew.j.moylan at gmail.com>
  • Date: Thu, 20 Mar 2008 02:51:41 -0500 (EST)

Two lists of integers:

{a, b} = Table[RandomInteger[10000, 1000], {2}];

Which elements from a are in b?

Select[a, MemberQ[b, #] &]; // Timing
>> {0.351, Null}

It takes about 0.351 seconds (on my slow laptop). Specialised
functions for related tasks, such as Intersection[a, b], are much
faster:

Intersection[a, b]; // Timing
>> {0., Null}

Using Intersection, here's a somewhat faster way to select those
elements from a that are in b:

With[
   {c = Intersection[a, b]},
   Select[a, MemberQ[c, #] &]
   ]; // Timing
>> {0.09, Null}

Is there a better, faster way to do this?


  • Prev by Date: smallest fraction
  • Next by Date: Re: Evaluation details
  • Previous by thread: Re: Re: Re: Re: smallest
  • Next by thread: Re: Fast way to select those elements from a list that are in another