1
$\begingroup$

I have the following nested list

{{{0.1,0.1, {{p->-4.01, g->0.93},{p->0.60, g->0.93}}},
 {0.1,0.2,  {{p->-4.54, g->0.93},{p->0.63, g->0.93}}}},
 {{0.2,0.1, {{p->-4.26, g->0.86},{p->1.62, g->0.86}}},
 {0.2,0.2,  {{p->4.91, g->0.84},{p->0.66, g->0.84}}}}}

(The true list is much longer). I would like to select the element of the list for which 0<= p <=1 and discard the other element of the sublist that contains a p>1 | p<0. This is what I want:

{{{0.1,0.1, {{p->0.60, g->0.93}}},
 {0.1,0.2,  {{p->0.63, g->0.93}}}},
 {0.2,0.2,  {{p->0.66, g->0.84}}}}}

This does almost what I want tbl = Select[tbl, #[[2]][[2]][[1]][[2]] > 0 && #[[2]][[2]][[1]][[2]] <= 1 &]; almost because it does not drop the non matching elements.

$\endgroup$
1
$\begingroup$

Try this:

list = {{{0.1, 0.1, {{p -> -4.01, g -> 0.93}, {p -> 0.60, g -> 0.93}}},
         {0.1, 0.2, {{p -> -4.54, g -> 0.93}, {p -> 0.63, g -> 0.93}}}},
        {{0.2, 0.1, {{p -> -4.26, g -> 0.86}, {p -> 1.62, g -> 0.86}}},
         {0.2, 0.2, {{p -> 4.91, g -> 0.84}, {p -> 0.66, g -> 0.84}}}}};

MapAt[DeleteCases[#, HoldPattern[{p -> pn_, g -> gn_}] /; ! (0 <= pn <= 1)] &, 
      list, {All, All, 3}]
   {{{0.1, 0.1, {{p -> 0.6, g -> 0.93}}},
     {0.1, 0.2, {{p -> 0.63, g -> 0.93}}}},
    {{0.2, 0.1, {}}, {0.2, 0.2, {{p -> 0.66, g -> 0.84}}}}}

DeleteCases[%, {_, _, {}}, {2}]
   {{{0.1, 0.1, {{p -> 0.6, g -> 0.93}}},
     {0.1, 0.2, {{p -> 0.63, g -> 0.93}}}},
    {{0.2, 0.2, {{p -> 0.66, g -> 0.84}}}}}
$\endgroup$
1
$\begingroup$

You may Select the items with MapAt at their location then Query the result to Select items from the first Select that are not empty.

Query[All, Select[Last@# != {} &]]@
 MapAt[Select[0 <= (p /. #) <= 1 &], {All, All, -1}]@list
{{{0.1, 0.1, {{p -> 0.6, g -> 0.93}}}, 
  {0.1, 0.2, {{p -> 0.63, g -> 0.93}}}}, 
 {{0.2, 0.2, {{p -> 0.66, g -> 0.84}}}}}

Hope this helps.

$\endgroup$

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.