2
$\begingroup$

For example, we have a list ={1,2,3,4,5,6}, we can use Cases[list,x_/; 3<x<10] to pick up {4,5,6}.

What if we are dealing with a nested list for example : list2={{0.1,0.2},{0.1,0.2},{0.2,0.3},{0.3,0.4}};

Shall I use something like Cases[list2,{x_,y_}/;0<x+y<0.5] to pick up {0.1,0.2}in this case?

$\endgroup$
4
  • 2
    $\begingroup$ yes - but in both of your examples Select seems more natural than Cases $\endgroup$
    – Jason B.
    Aug 18, 2017 at 22:20
  • $\begingroup$ I tried to build a complex nested list using this method, but get empty result that's why I ask this $\endgroup$
    – leon365
    Aug 18, 2017 at 22:24
  • $\begingroup$ First you have to make sure that your pattern matches the elements that you are trying to get. If it does, then you need to make sure that you are looking at the right level of your list. By default, Cases will match only at the top level: Cases[{{1},{2},{3}}, _Integer] will return {} because the elements at the top level would match {_Integer}. Cases[{{1}, {2}, {3}}, _Integer, 2], however, returns {1,2,3}. Look at the documentation for Cases, and look at the third argument in particular. $\endgroup$
    – Jason B.
    Aug 18, 2017 at 22:29
  • $\begingroup$ Thank you very much sir! $\endgroup$
    – leon365
    Aug 19, 2017 at 15:38

4 Answers 4

4
$\begingroup$

As @JasonB. mentions in the comments Select is an alternative that some say reads better.

Select[0 < Total@# < .5 &]@list2
{{0.1,0.2},{0.1,0.2}}

Hope this helps.

$\endgroup$
1
  • $\begingroup$ Thanks for the help! $\endgroup$
    – leon365
    Aug 19, 2017 at 15:37
2
$\begingroup$

You have answered your own question where you posted the question. Alternatively,

Cases[list2, x_ /; Plus @@ x < 0.5]
$\endgroup$
1
  • 2
    $\begingroup$ Total @ might be more natural than Plus @@ $\endgroup$
    – b3m2a1
    Aug 19, 2017 at 0:17
1
$\begingroup$

Yes looks correct, or you can put conditions on each one of the variables separated like that

Cases[list2, {x_, y_} /; x < 0.2 && y < 0.3]
$\endgroup$
1
$\begingroup$

If you have a nested list with elements of varying lengths:

list = {{0.1, 0.2, 0.0}, {{0.1, 0.2}}, {0.2, 0.3}, {0.3, 0.4}};

Cases[list, p : {__?NumericQ} /; Total@p < 0.5, -1]

{{0.1, 0.2, 0.}, {0.1, 0.2}}

$\endgroup$
1
  • $\begingroup$ Thanks for the supplement! $\endgroup$
    – leon365
    Aug 19, 2017 at 23:19

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.