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

2 Answers 2

11
$\begingroup$

You may try this:

Select[PrimeQ] /@ list
$\endgroup$
1
  • $\begingroup$ Thanks! Very short and good! $\endgroup$
    – user57467
    Nov 30, 2019 at 13:58
10
$\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$
    – user57467
    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$
    – kglr
    Dec 1, 2019 at 9:48

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.