3
$\begingroup$

I want to drop 2 continuous elements every 3 elements,such as I have a list:

list = {3, 5, 5, 5, 2, 5, 1, 0, 5, 0, 4};

I want to get

{3, 5, 5, 5, 1, 0, 4}

Any consice method can do this?

$\endgroup$
0

3 Answers 3

9
$\begingroup$

R.M's method with suitable modification:

Flatten @ Partition[list, 3, 5, 1, {}]
{3, 5, 5, 5, 1, 0, 4}

Or for recent versions of Mathematica using UpTo

Flatten @ Partition[list, UpTo[3], 5]
$\endgroup$
3
  • 1
    $\begingroup$ I used Mathematica for almost three years, but it is hard for me to think Partition can easily do this.. $\endgroup$
    – yode
    Mar 8, 2017 at 20:02
  • 1
    $\begingroup$ I just observed that using UpTo[3] instead of 3 slows down the solution with a factor 8 / 10. Therefore, for very long lists @rcollyer's solution Pick[list,PadRight[#,Length@list,#]&@UnitStep@Range[2,-2,-1],1] or this variant Pick[list, Clip[Mod[Range[Length[list]], 5], {2,3}], 2] could be considered as well. $\endgroup$ Mar 14, 2017 at 19:28
  • $\begingroup$ @Fred Interesting observation; thank you. Using variable length output in Partition slows it down to begin with, i.e. {} is slower than doing a PadRight on the original list then trimming after. I cannot remember where this was discussed but a search would probably find it. $\endgroup$
    – Mr.Wizard
    Mar 15, 2017 at 6:34
4
$\begingroup$
Flatten[Take[#, UpTo[3]] & /@ Partition[list, 5, 5, 1, {}]]

{3, 5, 5, 5, 1, 0, 4}

$\endgroup$
1
  • 1
    $\begingroup$ A small variant, for me easier to understand: Flatten[Take[#,UpTo[3]]&/@Partition[list,UpTo[5]]]. $\endgroup$ Mar 8, 2017 at 18:50
4
$\begingroup$
Flatten[Map[list[[# ;; ;; 5]] &, {1, 2, 3}], {2, 1}]

{3, 5, 5, 5, 1, 0, 4}

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.