Consider the following list:

{{0.1, 5}, {0.3, 18}, {0.4, 6}, {0.7, 9}, {1.1, 5}}

I want to obtain the second element of a sub-list with respect to the first element of the sub-list.

for example: given 0.4 I would like to retrieve 6, given 0.1 I would like to retrieve 5.

The first element in the sub-lists are monotonically increasing and non repetitive.

  • 2
    Have you tried anything? – Kuba May 16 at 13:55
  • 1
    @Kuba, now there are many things to try and to learn from. best – jarhead May 16 at 15:17
up vote 6 down vote accepted

Two possible examples (say for example you are interested in 0.1, but it works with any entry):

list = {{0.1, 5}, {0.3, 18}, {0.4, 6}, {0.7, 9}, {1.1, 5}};
Cases[list, {0.1, _}]
Select[list, #[[1]] == 0.1 &]

Edit: if you only want the second element, go for:

Cases[list, {0.1, _}][[1, 2]]
Select[list, #[[1]] == 0.1 &][[1, 2]]
  • 5
    Consider also Cases[list, {0.1, b_} -> b] to return only the second element of each sublist. – MarcoB May 16 at 14:05

Another approach is to convert your List to an Association:

list = {{0.1, 5}, {0.3, 18}, {0.4, 6}, {0.7, 9}, {1.1, 5}};
arse = AssociationThread @@ Transpose@list;
arse[0.4] (* 6 *)
arse[0.1] (* 5 *)

This assumes that each Key (each first element of a pair) are unique, but otherwise your question would be ill-posed.

  • Please, don't call associations that way... ;) – Henrik Schumacher May 16 at 15:21
  • @HenrikSchumacher Aah, I was going to ask for explanations (like it's a bad habit to call "association[something]`). Then I got it :D I'll edit to raise the ambiguity ;) – anderstood May 16 at 15:29
  • Not sure wether that is better... =D – Henrik Schumacher May 16 at 15:31
  • It raises the ambiguity! – anderstood May 16 at 15:32

Given that you only want the second element, and there are no repeats, you could use FirstCase

secondElement[firstElement_] := 
 FirstCase[{firstElement, other_} :> other]

secondElement[.1]@{{0.1, 5}, {0.3, 18}, {0.4, 6}, {0.7, 9}, {1.1, 5}}
(* 5 *)

secondElement[0.4]@{{0.1, 5}, {0.3, 18}, {0.4, 6}, {0.7, 9}, {1.1, 5}}
(* 6 *)
Pick [#[[All, 2]], #[[All, 1]], 0.4] &@lst

{6}

Pick [#[[All, 2]], #[[All, 1]], 0.1] &@lst

{5}

Pick [#[[All, 2]], #[[All, 1]], 0.1 | 0.4] &@lst 

{5, 6}

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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