list1 = {{"a",1},{"b",2},{"c",3}} 

I would like to delete any pair in list1 that does not have a first element that belongs to list2.

Example 1: If list2 = {"b"}, Output = {{"b",2}}
Example 2: If list2 = {"A","b"}, Output = {{"a",1},{"b",2}}

Here's what I have so far:

DeleteCases[list1,{#,_}/; !StringMatchQ[#,list2, IgnoreCase -> True]&].

I know this won't work (because StringMatchQ doesn't accept a list of values to compare to as a parameter, which leads me to thinking I need to Map the function above to list2.


You've almost got it:

list1 = {{"a", 1}, {"b", 2}, {"c", 3}};
list2 = {"A", "b"};

test = StringMatchQ[#, Alternatives @@ list2, IgnoreCase -> True] &;

Cases[list1, {_?test, _}]
{{"a", 1}, {"b", 2}}

A key element is clearly Alternatives.
I used Cases rather than DeleteCases as that seemed simpler to me.

The first part of my post is in direct answer to your question. Summary: use Alternatives, not Map.

Borrowing from belisarius' answer, if one is going to use ToLowerCase I propose this:

Pick[list1, list1[[All, 1]], Alternatives @@ ToLowerCase @ list2]

If some of the elements of list1 are not all lower case then:

Pick[list1, ToLowerCase @ list1[[All, 1]], Alternatives @@ ToLowerCase @ list2]


list1 = {{"a", 1}, {"b", 2}, {"c", 3}};
f[list1_, list2_] := Select[list1, MemberQ[ToLowerCase /@ list2, #[[1]]] &]
f[list1, {"A", "b"}]

(* {{"a", 1}, {"b", 2}} *)
  • $\begingroup$ That's nice too. I'd +1 but I'm out of votes for the day. (Remind me tomorrow.) $\endgroup$
    – Mr.Wizard
    Feb 21 '13 at 17:27
  • 1
    $\begingroup$ @Mr.Wizard Thanks :)I turned it to CW so neither of us will need to remember the nuisance :) $\endgroup$ Feb 21 '13 at 17:29
  • $\begingroup$ @belisarius - Very nice, thanks! $\endgroup$
    – tjm167us
    Feb 21 '13 at 17:43

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.