6
$\begingroup$

I am trying to use DeleteCase function but I don't know how to implement it in the way I need.

I have a list of sublists of numbers, for example:

{{1,1,1,1},{1,1,1,2},{4,2,5,1},{5,3,2,4}}

and I want to do is to delete all the sublists that contains an element greater than $4$.

The result would be like this:

{{1,1,1,1},{1,1,1,2}}

I am also avoiding loops or recursion.

$\endgroup$
1
  • 1
    $\begingroup$ Look up Condition and Max. $\endgroup$
    – Szabolcs
    Oct 2, 2017 at 16:37

5 Answers 5

4
$\begingroup$
 list = {{1, 1, 1, 1}, {1, 1, 1, 2}, {4, 2, 5, 1}, {5, 3, 2, 4}};    
 Select[list, Max[##] < 4 &]
$\endgroup$
4
$\begingroup$
lst = {{1, 1, 1, 1}, {1, 1, 1, 2}, {4, 2, 5, 1}, {5, 3, 2, 4}}; 

Pick[#, UnitStep[4 - Max /@ # ], 1] & @ lst
Pick[#, LessEqualThan[4] /@ Max /@ #]& @ lst 
Cases[lst, _?(Max @ # <= 4 &)]
DeleteCases[lst, _?(Max @ # > 4 &)]
Select[lst, Composition[LessEqualThan[4], Max]]

all give

{{1, 1, 1, 1}, {1, 1, 1, 2}}

$\endgroup$
3
$\begingroup$

Using GroupBy and Lookup:

Lookup[GroupBy[list, AllTrue[# <= 4 &]], True]

(*{{1, 1, 1, 1}, {1, 1, 1, 2}}*)

Using GatherBy:

GatherBy[list, AllTrue[# <= 4 &]][[1]]

(*{{1, 1, 1, 1}, {1, 1, 1, 2}}*)

Using ReplacePart and Position:

ReplacePart[list, Position[list, {___, a_, ___} /; a > 4] -> Nothing]

(*{{1, 1, 1, 1}, {1, 1, 1, 2}}*)

Using SplitBy:

SplitBy[list, AllTrue[# <= 4 &]][[1]]

(*{{1, 1, 1, 1}, {1, 1, 1, 2}}*)
$\endgroup$
2
$\begingroup$

I have added a sublist: {1,2,3,4} to the test cases which should be selected according to criterion stated in the OP.

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

DeleteCases[{___, a_, ___} /; a > 4][list]
DeleteCases[_?(AnyTrue[# > 4 &])][list]
Pick[list, FreeQ[_?(# > 4 &)] /@ list]
Pick[list, NoneTrue[# > 4 &] /@ list]
Pick[list, AllTrue[# <= 4 &] /@ list]
Select[AllTrue[# <= 4 &]][list]
Select[NoneTrue[# > 4 &]][list]
DeleteCases[list, _?(Or @@ 
     IntervalMemberQ[Interval[{5, ∞}], #] &)]

Result:

{{1, 1, 1, 1}, {1, 1, 1, 2}, {1, 2, 3, 4}}


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

Using Position and Delete

p = List @* First /@ Position[list, x_ /; x > 4]

{{3}, {4}}

Delete[p] @ list

{{1, 1, 1, 1}, {1, 1, 1, 2}}

$\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.