# How to find elements in a list by last two elements

I have a list list= {{a1, b1, c1}, {a2, b2, c2}, {a3, b3, c3},......} in which I want to find the element "an" by giving the values of {bn, cn} in the same order.

For example, if

list = {{1, 2, 3}, {4, 5, 6}, {7, 6, 5}}

For {5, 6}, I should get 4, not 7.

Thanks

list = {{1, 2, 3}, {4, 5, 6}, {7, 6, 5}};
asso = GroupBy[list, Rest -> First];
asso[{5, 6}]
(* {4} *)


If any $$\{b_n, c_n\}$$ occurs at most once, it's not necessary to have a list returned:

asso = GroupBy[list, Rest -> First, First];
asso[{5, 6}]
(* 4 *)


A simplified version of @kglr's function:

f[b_, c_] := Cases[list, {a_, b, c} -> a]

f[5, 6]
(*    {4}    *)


If you are sure that there is only one matching case, you can gain some speed by replacing Cases with FirstCase:

g[b_, c_] := FirstCase[list, {a_, b, c} -> a]

g[5, 6]
(*    4    *)

• I think I like this better than Coolwater's solution. Jan 31, 2021 at 13:34
• @J.M. it depends on the use case. If many pairs are to be looked up in the same list, then @Coolwater's one-time pre-grouping is the better answer. Jan 31, 2021 at 17:57
list//Pick[#[[All,1]],#[[All,2;;]], {5,6}]&


{4}

• Or list//Extract[#[[All,1]],Position[#[[All,2;;]], {5,6}]]& Feb 1, 2021 at 11:44
list = {{1, 2, 3}, {4, 5, 6}, {7, 6, 5}};


Using Extract

p = Append[1] /@ Position[list, {__, 5, 6}]


{{2, 1}}

Extract[list, p]


{4}

list = {{1, 2, 3}, {4, 5, 6}, {7, 6, 5}};


Using SequenceCases:

SequenceCases[list, {s : {_, 5, 6}} :> First@s]

(*{4}*)