7
$\begingroup$

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

$\endgroup$

5 Answers 5

9
$\begingroup$
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 *)
$\endgroup$
8
$\begingroup$

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    *)
$\endgroup$
2
  • $\begingroup$ I think I like this better than Coolwater's solution. $\endgroup$ Commented Jan 31, 2021 at 13:34
  • 1
    $\begingroup$ @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. $\endgroup$
    – Roman
    Commented Jan 31, 2021 at 17:57
4
$\begingroup$
list//Pick[#[[All,1]],#[[All,2;;]], {5,6}]&

{4}

$\endgroup$
1
  • $\begingroup$ Or list//Extract[#[[All,1]],Position[#[[All,2;;]], {5,6}]]& $\endgroup$
    – user1066
    Commented Feb 1, 2021 at 11:44
2
$\begingroup$
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}

$\endgroup$
2
$\begingroup$
list = {{1, 2, 3}, {4, 5, 6}, {7, 6, 5}};

Using SequenceCases:

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

(*{4}*)
$\endgroup$

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.