7
$\begingroup$

Suppose I have the following list

l={{"x","b","c"},{"y","a","d"},{"x","b","y"},{"x","y","c"}}

I want to go through the list l and delete elements whenever "x" and "y" appear both in a single sublist such that I get:

{{"x","b","c"},{"y","a","d"}}

Order does not matter, as long as "x" and "y" both exist.

$\endgroup$
1
  • 2
    $\begingroup$ Thanks for accepting an answer, but I think you were too hasty doing that. While accepting is one of the things to do after your question is answered, we recommend that users should test answers before voting and wait 24 hours before accepting the best one. That allows people in all timezones to answer your question and an opportunity for other users to point alternatives, caveats or limitations of the available answers. $\endgroup$
    – rhermans
    Aug 9, 2018 at 17:02

5 Answers 5

6
$\begingroup$

Something like the following?

l = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}};
DeleteCases[l, {OrderlessPatternSequence["x", "y", ___]}]

(* Out: {{“x”, “b”, “c”}, {“y”, “a”, “d”}} *)
$\endgroup$
3
  • $\begingroup$ Thank you for this. $\endgroup$
    – Wiliam
    Aug 9, 2018 at 16:49
  • $\begingroup$ @William you are very welcome. $\endgroup$
    – MarcoB
    Aug 9, 2018 at 17:20
  • $\begingroup$ @William Upvoting and accepting suffices. Comments are only for improvement suggestions, not "private messaging". $\endgroup$
    – user202729
    Aug 10, 2018 at 3:00
6
$\begingroup$
DeleteCases[l, _?(ContainsAll[{"x", "y"}])]

{{"x", "b", "c"}, {"y", "a", "d"}}

$\endgroup$
5
$\begingroup$

A different solution using SubsetQ and Select. I also prefer ti limit the scope of the variable definitions using With or Module.

With[
 {
  l = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}}
  },
 Select[l, Not[SubsetQ[#, {"x", "y"}]] &]
 ]
$\endgroup$
2
  • 2
    $\begingroup$ It's not documented, but SubsetQ supports an operator form, so you could eliminate the pure function and instead do Select[l, Not @* SubsetQ[{"x", "y"}]] $\endgroup$
    – Carl Woll
    Aug 9, 2018 at 18:07
  • 1
    $\begingroup$ @CarlWoll Nice tip. I really wish ! SubsetQ[{"x", "y"}] would work however. $\endgroup$
    – Mr.Wizard
    Aug 9, 2018 at 21:44
1
$\begingroup$
list = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}};

Using SequenceSplit (new in 11.3)

First @ SequenceSplit[list, {_?(ContainsAll[{"x", "y"}])}]

{{"x", "b", "c"}, {"y", "a", "d"}}

$\endgroup$
0
$\begingroup$
l = {{"x", "b", "c"}, {"y", "a", "d"}, {"x", "b", "y"}, {"x", "y", "c"}};

Using Pick:

Pick[#, Intersection[#1, #2] =!= #2 & @@@ Tuples[{#, Inactive@{"x", "y"}}]] &@l

(*{{"x", "b", "c"}, {"y", "a", "d"}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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