6
$\begingroup$

This is my very first question and I really appreciate this ability and thankful the community.

I have two lists and need to select only those pairs from the first list, first element of which is present in the second list:

I have:

listA = {{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}};
listB = {1, 3, 5}; 

I need to get

{{1, "a"}, {3, "c"}, {5, "e"}}
$\endgroup$

7 Answers 7

1
$\begingroup$

A short cut:

Extract[listA, List /@ listB]

{{1, "a"}, {3, "c"}, {5, "e"}}

$\endgroup$
3
$\begingroup$
Position[listA[[All,1]], Alternatives@@listB]//Extract[listA,#]&

(* {{1, a}, {3, c}, {5, e}} *)
$\endgroup$
2
$\begingroup$

One of many ways

listA = {{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}};
listB = {1, 3, 5};
Select[listA,MemberQ[listB,First[#]]&]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ this is precisely what I was looking for! Thank you! $\endgroup$ Commented Nov 30, 2022 at 5:03
2
$\begingroup$

Here is one way to do it:

listA = {{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}};
listB = {1, 3, 5};
DeleteCases[listA, _?(! MemberQ[listB, First@#] &)]

OR

Cases[listA, {a_, _} /; MemberQ[listB, a]]

OR

Select[listA, IntersectingQ[{First@#}, listB] &]

Result:

{{1, "a"}, {3, "c"}, {5, "e"}}

$\endgroup$
3
  • $\begingroup$ Thank you, Syed. This works, but I was playing with Select and am happy Nasser has a solution I was looking for! $\endgroup$ Commented Nov 30, 2022 at 5:04
  • $\begingroup$ Sorry, I did not notice the other two methods you listed. Perfect! Thank you $\endgroup$ Commented Nov 30, 2022 at 5:19
  • $\begingroup$ @IgorBinder, please wait for a day and then select an answer. What is perfect for one scenario may not be so for another. $\endgroup$
    – Syed
    Commented Nov 30, 2022 at 5:24
1
$\begingroup$

Using Cases, FreeQ and Condition:

Cases[listA, {x_, y_} /; ! FreeQ[listB, x]]
(*{{1, "a"}, {3, "c"}, {5, "e"}}*)
$\endgroup$
1
$\begingroup$
☺ = #[[#2]] &;

listA ~☺~ listB
{{1, "a"}, {3, "c"}, {5, "e"}}
$\endgroup$
0
$\begingroup$

Here we can use <| |>

{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}, {5, "e"}} //
Rule@@@#& //
Apply[Association] //
KeyTake[{1,3,5}] //
KeyValueMap[List]

{{1, a}, {3, c}, {5, e}}

$\endgroup$
2
  • $\begingroup$ (With the caveat that you need the keys (first entry in the list) to be unique; if they are not, then entries may be lost.) $\endgroup$ Commented Dec 1, 2022 at 18:03
  • $\begingroup$ @JoshuaSchrier in that case, for example, <| 1 -> {"a", "b"} |> could work for dup keys. $\endgroup$ Commented Dec 2, 2022 at 4:58

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.