4
$\begingroup$

some help is needed to address an issue that even though I have been searching around I have not been able to fix it the way I want (I am a novice to Mathematica). I need to filter out sublists of a nested list while maintaining the nested list level. E.g., I have the following list (Matrix) :

Matrix = {
 {
  {
   {O1,2,22,24,28,14,D1},
   {O1,1,21,23,27,13,D1},
   {O1,2,22,24,28,27,13,D1},
   {O1,2,22,24,28,14,13,D1},
   {O1,2,22,24,23,27,13,D1},
   {O1,2,22,21,23,27,13,D1},
   {O1,2,1,21,23,27,13,D1},
   {O1,1,21,23,27,28,14,D1},
   {O1,1,21,23,27,13,14,D1},
   {O1,1,21,23,24,28,14,D1},
   {O1,1,21,22,24,28,14,D1},
   {O1,1,2,22,24,28,14,D1},
   {O1,2,22,24,28,27,13,14,D1},
   {O1,2,22,24,23,27,28,14,D1},
   {O1,1,2,22,21,23,25,9,10,26,24,28,18,17,27,13,14,D1},
   {O1,1,2,22,21,23,25,9,10,26,24,28,16,15,27,13,14,D1},
   {O1,1,2,22,21,23,25,7,8,26,24,28,20,19,27,13,14,D1},
   {O1,1,2,22,21,23,25,7,8,26,24,28,18,PoP2,17,27,13,D1},
   {O1,1,2,22,21,23,25,7,8,26,24,28,18,17,27,13,14,D1},
   {O1,1,2,22,21,23,25,7,8,26,24,28,16,15,27,13,14,D1},
   {O1,1,2,22,21,23,5,PoP1,6,24,28,18,PoP2,17,27,13,14,D1},
   {O1,2,1,21,22,24,26,12,11,25,23,27,17,PoP2,18,28,14,13,D1},
   {O1,2,1,21,22,24,26,10,9,25,23,27,17,PoP2,18,28,14,13,D1},
   {O1,2,1,21,22,24,26,8,7,25,23,27,17,PoP2,18,28,14,13,D1},
   {O1,1,2,22,21,23,25,11,12,26,24,28,18,PoP2,17,27,13,14,D1},
   {O1,1,2,22,21,23,25,9,10,26,24,28,18,PoP2,17,27,13,14,D1},
   {O1,1,2,22,21,23,25,7,8,26,24,28,18,PoP2,17,27,13,14,D1}
  }
 }
}

the point is to select those sublists that contain an ordered sequence of PoP1,PoP2 and exclude the rest while still maintaining the list level, in this case it would be only the following:

{{{{O1,1,2,22,21,23,5,PoP1,6,24,28,18,PoP2,17,27,13,14,D1}}}}

but the actual list is in fact much bigger. I have tried with the following

Select[Flatten[Matrix, {1, 2, 3}], ContainsAll[{PoP1, PoP2}]] 

but this is not correct due to missing orderliness while the other one is not working

Select[Flatten[Matrix, {1, 2, 3}], {PatternSequence[_, (PoP1 & PoP2)]}]

Any help is really appreciated.

$\endgroup$
5
$\begingroup$

DeleteCases deletes patterns without modifying the list structure. So, just apply DeleteCases at level {-2}:

DeleteCases[Matrix, Except@{___,PoP1,___,PoP2,___}, {-2}]

{{{{O1, 1, 2, 22, 21, 23, 5, PoP1, 6, 24, 28, 18, PoP2, 17, 27, 13, 14, D1}}}}

$\endgroup$
  • $\begingroup$ Works great! Thanks a lot Sir. $\endgroup$ – Besi Oct 23 '18 at 18:49

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.