5
$\begingroup$

I have two lists:

a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
b = {11, 8, 13};

I'm looking for a clean way to drop all elements of a which contain an element from b. The desired output for this example would be

c = {{4, 5, 6}}

where a[[2]] and a[[3]] have been dropped because they contain elements 8 and 11 from b.

Any help would be greatly appreciated!

$\endgroup$
  • 1
    $\begingroup$ c=DeleteCases[a, lis_ /; MemberQ[lis, Alternatives @@ b]]... $\endgroup$ – ciao Feb 5 '17 at 4:24
  • $\begingroup$ Awesome! Thanks so much! If you post this as a solution I'd love to give you credit. :) $\endgroup$ – tquarton Feb 5 '17 at 4:25
  • $\begingroup$ Don't worry about it, but thanks for sentiment. $\endgroup$ – ciao Feb 5 '17 at 4:28
7
$\begingroup$
a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {1, 2, 3}, {11, 12, 13}};
b = {11, 8, 13};

Select[a, DisjointQ[b, #] &]

Select[a, {} == b ⋂ # &]
{{4, 5, 6}, {1, 2, 3}}

{{4, 5, 6}, {1, 2, 3}}

DisjointQ introduced in Mathematica 10. Use the second line in earlier versions.


Actually the second line appears to be faster in every test I have performed so I would use it regardless of version. For example:

SeedRandom[1]

a = RandomInteger[999, {5000, 100}];
b = {11, 8, 13};

Select[a, DisjointQ[b, #] &]  // Length // RepeatedTiming

Select[a, {} == b ⋂ # &]      // Length // RepeatedTiming
{0.11, 3686}

{0.0286, 3686}

In this particular case using Alternatives falls somewhere in the middle:

Select[a, FreeQ[Alternatives @@ b]] // Length // RepeatedTiming
{0.0463, 3686}

Due to its early exit behavior in a case where most of the lists will be rejected it pulls ahead:

SeedRandom[1]

a = RandomInteger[99, {5000, 100}];

Select[a, {} == b ⋂ # &]             // Length // RepeatedTiming
Select[a, FreeQ[Alternatives @@ b]]  // Length // RepeatedTiming
{0.0291, 223}

{0.0247, 223}
$\endgroup$
3
$\begingroup$

ciao doesn't want to make the effort to write an answer, but it is better for a question to have an real answer than a comment answer, so here is his answer.

a = {{4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {1, 2, 3}, {11, 12, 13}};
b = {11, 8, 13};
DeleteCases[a, lis_List /; MemberQ[lis, Alternatives @@ b]]

{{4, 5, 6}, {1, 2, 3}}

$\endgroup$
  • $\begingroup$ "ciao doesn't want to make the effort ...". Ouch, man, just ouch... $\endgroup$ – ciao Feb 5 '17 at 5:25
  • $\begingroup$ @ciao. Sorry that it hurts, but is it not the simple truth? $\endgroup$ – m_goldberg Feb 5 '17 at 5:31
  • $\begingroup$ @ciao. I'll delete this answer if you would prefer to see it gone now that Mr.Wizard has answered $\endgroup$ – m_goldberg Feb 5 '17 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.