6
$\begingroup$

I am new in Wolfram Math and I need a help in making a simple program. Let's suppose we have a list:

list = {{1, 11}, {2, 7}, {4, 2}, {7, 9}, {-2, 3}, {-1, 10}};

Now, I need to collect the first elements of sublists, but not all of them, only those whose second elements are larger than 8.

Thanks in advance.

$\endgroup$
6
$\begingroup$
list = {{1, 11}, {2, 7}, {4, 2}, {7, 9}, {-2, 3}, {-1, 10}};

Select[list, #[[2]] > 8 &][[All, 1]]

{1, 7, -1}

OR using Pick

Pick[list[[All, 1]], UnitStep[list[[All, 2]] - 8], 1]

{1, 7, -1}

$\endgroup$
  • $\begingroup$ @Suro. You're welcome, glad I could help. $\endgroup$ – RunnyKine Apr 18 '16 at 11:43
6
$\begingroup$
list = {{1, 11}, {2, 7}, {4, 2}, {7, 9}, {-2, 3}, {-1, 10}};
Cases[list, {a_, b_} /; b > 8 :> a]
(* {1, 7, -1} *)

What I'm doing above is to use Cases to select only those sublists whose second element is greater than 8,

Cases[list, {a_, b_} /; b > 8]
(* {{1, 11}, {7, 9}, {-1, 10}} *)

The /; notation defines a Condition. Then I'm applying a :> to make a replacement, in this case keeping only the first element, look at RuleDelayed

$\endgroup$
2
$\begingroup$

Mathematica/Wolfram Language provides a lot of flexibility. Some ways you could do this:

Cases[list, {x_, _?(# > 8 &)} :> x]
Select[list, #[[2]] > 8 &][[;; , 1]]
Pick[list, #[[2]] > 8 & /@ list][[;; , 1]]
True /. GroupBy[list, (#[[2]] > 8 &) -> (#[[1]] &)]
Flatten[Last@Reap[Sow @@@ list, _?(# > 8 &), #2 &]]

I encourage you to look the documentation and play. You can find the way that suits your aims and/or style.

and some more ridiculous:

Cases[{#1, Sign[#2 - 8]} & @@@ list, {x_, 1} :> x]
f[x_, y_] := x /; y > 8
f[__] := Sequence[]
f @@@ list
$\endgroup$
  • $\begingroup$ Your advice is highly appreciated. Thanks. $\endgroup$ – Suro Apr 18 '16 at 11:50
1
$\begingroup$
Pick[list[[All, 1]], # > 8 & /@ list[[All, 2]]]

or

Pick[#[[1]], # > 8 & /@ #[[2]]] &@Transpose[list]

{1, 7, -1}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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