7
$\begingroup$

I have been looking at Span, Take, etc. functions but I couldn't figure out how can I extract elements likes this

A = {a, b, c, d, e, f, g, h, k, l, m, n, o, p}

And I want this : A' = {b, c, f, g, l, m}.

Basically, I am looking at the elements with a distance of 4 + their next elements: {b, f, l} + their associated next elements {c, g, m}

Thanks!

$\endgroup$
5
$\begingroup$
Flatten @ Partition[Rest @ A, 2, 4]

{b, c, f, g, l, m}

or

A[[Flatten @ Partition[Range[2, Length @ A], 2, 4]]]

{b, c, f, g, l, m}

Also

Table[Sequence @@ A[[{i + 1, i + 2}]], {i, 1 , Length[A] - 2, 4}]

{b, c, f, g, l, m}

$\endgroup$
4
$\begingroup$

This returns the 2nd and 3rd elements from successive 4-element chunks, and is directly generalizable to any chunk size or element selection:

Flatten@Map[{#[[2]], #[[3]]} &, Partition[A, 4]]

{b, c, f, g, l, m}

Same as above, using shorthand for Map:

Flatten[{#[[2]], #[[3]]} & /@ Partition[A, 4]]

{b, c, f, g, l, m}

This gives the first letter of the pair at the end without its mate, so to eliminate it you'd need to drop the last letter:

Riffle[Downsample[A, 4, 2], Downsample[A, 4, 3]]
Drop[Riffle[Downsample[A, 4, 2], Downsample[A, 4, 3]],-1]

{b, c, f, g, l, m, p}

{b, c, f, g, l, m}

Similarly:

Drop[{Downsample[A, 4, 2], Downsample[A, 4, 3]}~Flatten~{2, 1}, -1]

{b, c, f, g, l, m}

$\endgroup$
2
$\begingroup$

Try this simpler one:

 Flatten[Table[{A[[i]], A[[i+1]]},{i,2,Length[A]-1,4}]]

Flatten is used to remove curly brackets.

$\endgroup$
1
$\begingroup$
Riffle[A[[2 ;; ;; 4]], A[[3 ;; ;; 4]]];

or

Flatten[Transpose[{A[[2 ;; ;; 4]], A[[3 ;; ;; 4]]}]]

The latter is easily generalizable to more than two "spans".

Also notable:

Flatten[Partition[A, 4][[All, 2 ;; 3]]]

For unpacked list A, the method with Riffle seems to be the best among these (on my machine). For packed integer list A, second method seems to be a bit faster.

$\endgroup$
  • 2
    $\begingroup$ To the downvoter: Is something not right with this answer? $\endgroup$ – Henrik Schumacher Aug 6 at 15:23

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.