3

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?

yode
  • 26,686
  • 4
  • 62
  • 167

3 Answers3

9

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]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 1
    I used Mathematica for almost three years, but it is hard for me to think Partition can easily do this.. – yode Mar 08 '17 at 20:02
  • 1
    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. – Fred Simons Mar 14 '17 at 19:28
  • @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. – Mr.Wizard Mar 15 '17 at 06:34
4
Flatten[Take[#, UpTo[3]] & /@ Partition[list, 5, 5, 1, {}]]

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

Chris Degnen
  • 30,927
  • 2
  • 54
  • 108
4
Flatten[Map[list[[# ;; ;; 5]] &, {1, 2, 3}], {2, 1}]

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

Coolwater
  • 20,257
  • 3
  • 35
  • 64