10
$\begingroup$

I want to use Select or Pick for selecting primes in all sublists.

list = {{2, 3, 4, 5, 7}, {8, 9, 11}, {16, 17, 18}} 

I can do it by

Table[Select[list[[k]], PrimeQ], {k, 3}] 

or

Map[If[PrimeQ[#], #] &] /@ list /. Null -> Sequence[] 

resulting in both cases in

{{2, 3, 5, 7}, {11}, {17}} 

But I want to use Select or Pick for unknown values of k.

$\endgroup$

5 Answers 5

13
$\begingroup$

You may try this:

Select[PrimeQ] /@ list 
$\endgroup$
1
  • $\begingroup$ Thanks! Very short and good! $\endgroup$ Commented Nov 30, 2019 at 13:58
12
$\begingroup$

You can also use Pick with PrimeQ @ list as the selector array:

Pick[#, PrimeQ @ #] & @ list 

{{2, 3, 5, 7}, {11}, {17}}

or Cases:

Cases[_?PrimeQ] /@ list 

{{2, 3, 5, 7}, {11}, {17}}

$\endgroup$
2
  • $\begingroup$ Your first solution works fine, but to be honest: i don't understand the syntax! Your second solution worked for Cases[list, _?PrimeQ] on one dimesional list $\endgroup$ Commented Dec 1, 2019 at 8:51
  • $\begingroup$ @user57467, re the first method, Pick[#, PrimeQ @ #] & @ list is the same as Pick[list, PrimeQ @ list]. Cases[_?PrimeQ] /@ list should work for list of lists in versions 10+. $\endgroup$ Commented Dec 1, 2019 at 9:48
2
$\begingroup$
list = {{2, 3, 4, 5, 7}, {8, 9, 11}, {16, 17, 18}}; 

Using Replace at level 2:

Replace[list, n_ /; ! PrimeQ[n] -> Nothing, {2}] (*{{2, 3, 5, 7}, {11}, {17}}*) 
$\endgroup$
2
$\begingroup$
list = {{2, 3, 4, 5, 7}, {8, 9, 11}, {16, 17, 18}}; 

Using SequenceSplit (new in 11.3)

Join @@ SequenceSplit[#, {_?(Not @* PrimeQ)}] & /@ list 

{{2, 3, 5, 7}, {11}, {17}}

Using Position and Delete

p = Position[list, x_ /; ! PrimeQ[x], 2, Heads -> False] 

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

Delete[p] @ list 

{{2, 3, 5, 7}, {11}, {17}}

$\endgroup$
1
$\begingroup$

Using DeleteCases:

DeleteCases is suitable for nested lists as is maintains list structure while deleting any elements that match the pattern.

list = {{2, 3, 4, 5, 7}, {8, 9, 11}, {16, 17, 18}} DeleteCases[list, _?(Not@*PrimeQ), All] 

{{2, 3, 5, 7}, {11}, {17}}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.