Suppose I have the following list
lis = Range[100];
and I want to remove n consecutive terms periodically from the list. For example suppose I want to drop terms 4 and 5, 9 and 10, 14 and 15 etc. I could do this sequentially as follows:
Drop[Drop[lis, {5, -1, 5}], {4, -1, 4}];
This gives:
{1, 2, 3, 6, 7, 8, 11, 12, 13, 16, 17, 18, 21, 22, 23, 26, 27, 28,
31, 32, 33, 36, 37, 38, 41, 42, 43, 46, 47, 48, 51, 52, 53, 56, 57,
58, 61, 62, 63, 66, 67, 68, 71, 72, 73, 76, 77, 78, 81, 82, 83, 86,
87, 88, 91, 92, 93, 96, 97, 98}
This gets really messy if I have to drop n
consecutive terms where n
is large. Is there a way to do this with just one Drop
function or a better more compact and efficient way to achieve this where my list is huge. In my example above, n
is 2
, but it could be 3
, 4
etc. What I want is a general solution. Thanks.
Answer
The simplest (and probably fastest) way is to use Partition
with the appropriate offset:
list = Range@100;
Flatten@Partition[list, 3, 5]
(* {1, 2, 3, 6, 7, 8, 11, 12, 13, 16, 17, 18, 21, 22, 23, 26, 27, 28,
31, 32, 33, 36, 37, 38, 41, 42, 43, 46, 47, 48, 51, 52, 53, 56, 57,
58, 61, 62, 63, 66, 67, 68, 71, 72, 73, 76, 77, 78, 81, 82, 83, 86,
87, 88, 91, 92, 93, 96, 97, 98} *)
The logic is: "Take 3, drop 2, take 3, drop 2,... " till the end of the list (the argument 5
is just 3+2
). You can change these numbers as desired.
Comments
Post a Comment