Say I have a long list with 1000 elements and I want to periodically delete groups of elements based off of two variables.
So for my_list=[1,2,3,4...1000]
, and a=5
, b=7
, I would keep the first 5 elements, delete the next 7, and repeat until the end of the list.
The list will then look like:
my_list = [1,2,3,4,5,12,13,14,15,16...]
I don't know a or b prior to using them, nor the length of the list, so I'm looking for a general solution.
Thanks!
Here's one way to do it using enumerate
and taking the mod
of the index on the sum of a
and b
. Filter out values whose mod is less than a
:
l = range(1, 30)
a, b = 5, 7
r = [x for i, x in enumerate(l) if i%(a+b) < a]
print(r)
# [1, 2, 3, 4, 5, 13, 14, 15, 16, 17, 25, 26, 27, 28, 29]
PS if you're deleting the next 7, 12 should not be included.
Here's a different approach using iterators:
import itertools as it
L = list(range(1000))
a, b = 5, 7
mask = it.chain(it.repeat(1, a), it.repeat(0, b))
Result = list(it.compress(L, it.cycle(mask)))
Documentation of the itertools
standard module .
The cool thing here is that no intermediate data is stored in memory, and all the results are generated on-the-fly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.