I have a python array of a certain number of elements and I want to keep 5 elements, then discard 15, keep 5, discard 15, etc.
Is there a fast way to do this?
CodePudding user response:
You can use a good old list comprehension and enumerate
. Take the modulo. Values 1-5 are modulo 0-4:
[v for i,v in enumerate(your_list) if i%(15 5)<5]
Example:
your_list = list(range(100))
[v for i,v in enumerate(your_list) if i%20<5]
output:
[0, 1, 2, 3, 4, 20, 21, 22, 23, 24, 40, 41, 42, 43, 44, 60, 61, 62, 63, 64, 80, 81, 82, 83, 84]
CodePudding user response:
You can use simple slicing and appropriate start/stop/step calculations:
arr = list(range(100))
from itertools import chain
take, skip = 5, 15
list(chain.from_iterable(arr[i:i take] for i in range(0, len(arr), take skip)))
# [0, 1, 2, 3, 4,
# 20, 21, 22, 23, 24,
# 40, 41, 42, 43, 44,
# 60, 61, 62, 63, 64,
# 80, 81, 82, 83, 84]
CodePudding user response:
If you use numpy
.
Given that l
is:
l = np.arange(100)
Use:
>>> np.split(l, range(5, len(l), 5))[::4]
[array([0, 1, 2, 3, 4]), array([20, 21, 22, 23, 24]), array([40, 41, 42, 43, 44]), array([60, 61, 62, 63, 64]), array([80, 81, 82, 83, 84])]
>>>
For an 2d array instead of a list of 1d arrays, try:
>>> np.array(np.split(l, range(5, len(l), 5))[::4])
array([[ 0, 1, 2, 3, 4],
[20, 21, 22, 23, 24],
[40, 41, 42, 43, 44],
[60, 61, 62, 63, 64],
[80, 81, 82, 83, 84]])
>>>
CodePudding user response:
The following solution, in addition to not using any import, is also quite fast:
def skip_elements(l, n1, n2):
i1 = range(len(l))[::n1 n2]
i2 = [x n1 for x in i1]
return [l[x:y] for x, y in zip(i1, i2)]
test = list(range(1011))
n_elements_to_keep = 5
n_elements_to_skip = 15
print(skip_elements(test, n_elements_to_keep, n_elements_to_skip))
If you need the result as one list (rather that a list of lists), you can change the return
statement in def skip_elements
as follows:
return sum([l[x:y] for x, y in zip(i1, i2)],[])
Anyway, if you need a list of lists, this is the fastest solution from what I can see. Vice versa, if one list is the desired output, the itertools
one is the best. Despite being quite elegant (I must admit - I voted it ), the list comprehension one is the slowest among the ones shown.