Home > Mobile >  Python list: after m items skip n items
Python list: after m items skip n items

Time:06-04

Suppose we have the following list:

x=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

After m=3items, we would like to skip n=2 items so that we have the following list:

x=[0, 1, 2, 5, 6, 7]

CodePudding user response:

You can use enumerate and mods to achieve this:

num_to_skip = 2
num_to_retain = 3
length = num_to_skip   num_to_retain
# the remainders of the indexes to exclude from the list
exclude_remainders = list(range(num_to_retain, length))

xs = list(range(10))
zs = [
  x for i, x in enumerate(xs) 
  if i % length not in exclude_remainders
]

# => [0, 1, 2, 5, 6, 7]                                                                                                                                                                                         

i.e. what this is doing is:

     0  1  2  3  4   5  6  7  8  9   10 11 ->
1.  [-------------] [-------------] [----->
2.           [----]          [----]

1 - for each of these sets:
2 - exclude the values where the remainder obtained by modding the 
    index against the length of the set is not in a list of 
    remainders to exclude

i.e. exclude the following:
index % 5 == 3, and
index % 5 == 4

CodePudding user response:

You can make a list of slices and then flatten it:

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

take = 3
skip = 2

[n for i in range(0, len(x), take skip) 
 for n in x[i: i   take]]
# [0, 1, 2, 5, 6, 7, 10, 11, 12, 15]

This iterates over the range by 5 (take skip) and then takes the first three starting at that index.

  • Related