3
$\begingroup$

I have:

aa = {{1, 1}, {2, 2}}

bb = {{4, 4}, {5, 5}}

cc = {{a, {1, 1}}, {b, {2, 2}}, {c, {3, 3}}, {d, {4, 4}}, {e, {5, 5}}, {f, {6, 6}}}

How can I select all elements form cc that contain all elements from aa as well as from bb?

The result should be:

{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}
$\endgroup$
  • 5
    $\begingroup$ ... if you've already assigned values to a and b, they will not show up in c. $\endgroup$ – J. M. is away Sep 13 '17 at 16:34
  • $\begingroup$ sorry for the mistake ... $\endgroup$ – mrz Sep 13 '17 at 18:11
4
$\begingroup$

You may use ContainsAny.

Select[cc, ContainsAny[Join[aa, bb]]]
{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}

Hope this helps.

$\endgroup$
5
$\begingroup$

Noting J.M.'s observation in the comments, I redefined your lists as

aa = {{1, 1}, {2, 2}};
bb = {{4, 4}, {5, 5}};
cc = {{a, {1, 1}}, {b, {2, 2}}, {c, {3, 3}}, {d, {4, 4}}, {e, {5, 5}}, {f, {6, 6}}};

Then,

Cases[cc, {_, Alternatives @@ Join[aa, bb]}, {1}]
(* {{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}} *)
$\endgroup$
3
$\begingroup$

Several methods in addition to Cases in @march's answer:

Select[cc, MemberQ[Join[aa, bb], #[[2]]] &]
Pick[cc,  MemberQ[Join[aa, bb], #[[2]]] & /@ cc]
DeleteCases[cc, _?(! MemberQ[Join[aa, bb], #[[2]]] &)]

{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}

$\endgroup$
3
$\begingroup$
Select[cc, MemberQ[Join @@ Thread[aa | bb]]]
{{a, {1, 1}}, {b, {2, 2}}, {d, {4, 4}}, {e, {5, 5}}}
$\endgroup$
  • $\begingroup$ Also ContainsAny[Join[aa, bb]]. $\endgroup$ – Edmund Sep 13 '17 at 23:31
  • $\begingroup$ @Edmund Nice, but unfortunately not available in version 10.1 which I use. $\endgroup$ – Mr.Wizard Sep 13 '17 at 23:39
  • 2
    $\begingroup$ Can't you offer WRI some rep for an upgrade? $\endgroup$ – Edmund Sep 13 '17 at 23:41
  • $\begingroup$ @Edmund: Please add your ContainsAny-Solution as an answer ... I like it very much. $\endgroup$ – mrz Sep 14 '17 at 7:41
2
$\begingroup$

It is also possible by using rules:

cc /. {s_Symbol, pair_List} /; !MemberQ[Join[aa, bb], pair] -> Nothing
$\endgroup$

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.