2
$\begingroup$

Say we have a list

{{415., {{1, 1}, {24, 67}, {17, 83}}}, {371., {{24, 67}, {17, 83}, {3,9}}}, {370., {{4, 7}, {24, 67}, {17, 83}}}, {365.5, {{24,67}, {17, 83}, {5, 6}}}, {124., {{1, 1}, {17, 83}, {5, 6}}}, {95., {{17, 83}, {5, 6}, {3, 9}}}, {89.5, {{24, 67}, {5, 6}, {3, 9}}}, {75., {{1, 1}, {4, 7}, {17, 83}}}

I want to take the first 3 elements of the list where the first value is > 100, so in this example

{{415., {{1, 1}, {24, 67}, {17, 83}}}, {371., {{24, 67}, {17, 83}, {3,9}}}, {370., {{4, 7}, {24, 67}}

. However if I have list like

{{11., {{1, 1}, {5, 6}, {3, 9}}}, {6., {{1, 1}, {4, 7}, {3, 9}}}, {4.5, {{1, 1}, {5, 6}, {4, 7}}}, {0.5, {{5, 6}, {4, 7}, {3, 9}}}}

I want to print an error like "No value > 100 found" . Any hints on how to do this??

$\endgroup$
1
  • 3
    $\begingroup$ Something like result=Select[list,First[#]>100&]; If[Length[result]>=3,Take[result,3],Print[ "No value > 100 found"]] ? Test that very carefully to try to make certain it is correct in all cases. Then you can fiddle with the logic to try to get the error message to be as close to exactly what you want as possible. $\endgroup$
    – Bill
    Nov 7, 2020 at 2:07

1 Answer 1

4
$\begingroup$
ClearAll[f]
f[l_, t_, n_] := Select[l, GreaterThan[t]@First[#] &, n] /. 
   {} -> StringTemplate["No value > `` found"]@t

Examples:

lst1 = {{415., {{1, 1}, {24, 67}, {17, 83}}}, {371., {{24, 67}, {17, 
      83}, {3, 9}}}, {370., {{4, 7}, {24, 67}, {17, 
      83}}}, {365.5, {{24, 67}, {17, 83}, {5, 6}}}, {124., {{1, 
      1}, {17, 83}, {5, 6}}}, {95., {{17, 83}, {5, 6}, {3, 
      9}}}, {89.5, {{24, 67}, {5, 6}, {3, 9}}}, {75., {{1, 1}, {4, 
      7}, {17, 83}}}};

lst2 = {{11., {{1, 1}, {5, 6}, {3, 9}}}, {6., {{1, 1}, {4, 7}, {3, 
      9}}}, {4.5, {{1, 1}, {5, 6}, {4, 7}}}, {0.5, {{5, 6}, {4, 
      7}, {3, 9}}}};

f[lst1, 100, 3]
{{415., {{1, 1}, {24, 67}, {17, 83}}}, {371., {{24, 67}, {17, 83}, {3,  9}}}, 
 {370., {{4, 7}, {24, 67}, {17, 83}}}}
f[lst2, 100, 3]
 "No value > 100 found"
$\endgroup$

Your Answer

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