4
$\begingroup$

I would like to make a sublist consisting of the four elements that follow each occurrence of 1, 2 in the list:

lis = {a, b, 1, 2, c, d, e, f, g, 1, 2, w, x, y , z, q, r}

to make:

res = {{c, d, e, f}, {w, x, y, z}}

Thanks for any thoughts.

$\endgroup$
6
$\begingroup$
Cases[{2, p__} /; Length[{p}] >= 4 :> {p}[[;; 4]]] @ 
  Rest @ Split[lis, {#, #2} =!= {1, 2} &]
{{c, d, e, f}, {w, x, y, z}}

And a variation:

Cases[{2, p__} /; Length[{p}] >= 4 :> Take[{p}, 4]] @ 
  Rest @ Split[lis, {#, #2} =!= {1, 2} &]
{{c, d, e, f}, {w, x, y, z}}
$\endgroup$
3
  • 2
    $\begingroup$ +1, but both solutions will fail in the cases like lis = {2, a, b, f, h, 1, 2, c, d, e, f};. $\endgroup$ Aug 29 at 7:45
  • 1
    $\begingroup$ Thank you @AlexeyPopkov; good catch. Looks like wrapping Split with Rest fixes the issue. $\endgroup$
    – kglr
    Aug 29 at 8:00
  • 1
    $\begingroup$ Good idea with Rest! Probably more efficient version: Cases[{2, p : Repeated[_, {4}], ___} :> {p}]@Rest@Split[lis, {#, #2} =!= {1, 2} &]. $\endgroup$ Aug 29 at 8:45
8
$\begingroup$

An alternative solution to @TumbiSapichu's one:

SequenceCases[lis, {1, 2, p : Repeated[_, {4}]} :> {p}]
(* {{c, d, e, f}, {w, x, y, z}} *)
$\endgroup$
8
$\begingroup$

Something like this?

res = #[[-4 ;;]] & /@ SequenceCases[lis, {1, 2, _, _, _, _}]
(*{{c, d, e, f}, {w, x, y, z}}*)
$\endgroup$
1
$\begingroup$
(lis // SequencePosition[#,{1,2}][[All,2]]& // {1 + #,4 + #}&// Transpose) 
// Map[Take[lis,#]&]

(* {{c, d, e, f}, {w, x, y, z}} * )
$\endgroup$
1
$\begingroup$
lis[[# + 1 ;; # + 4]] & /@ (#[[2]] & /@ SequencePosition[lis, {1, 2}])
$\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.