Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping Select of one list over a second list

I have a large multi column data file, but for this question it can simplified as follows:

data = {{"a", 2000}, {"a", 2010}, {"b", 1999}, {"b", 2004}, {"b", 
2006}, {"c", 2012}, {"c", 2014}};

I then have a list of items for which I want to extract the year value from data, e.g:

selectedList = {"b", "c"};

I can do it by using Select[] and then iterating through the selectedList:

Table[
        Select[data, #[[1]] == selectedList[[i]] &][[All, 2]],

       {i, 1, Length[selectedList]}  ]

However I want to use Map, which should be faster than Table. I can do this:

func[dat_, x_] := Select[dat, #[[1]] == x &][[All, 2]]

and then :

func[data, #] & /@ selectedList

I am looking for a more elegant way to do this in one step, preferably mapping Select directly onto selectedList

like image 275
BlueMac Avatar asked Dec 07 '22 15:12

BlueMac


1 Answers

Cases[data, {#, x_} :> x] & /@ selectedList
like image 145
681234 Avatar answered Jan 07 '23 03:01

681234