简体   繁体   中英

Skipping n elements iteratively while slicing a list in python

I have a big array of 10573 elements and I want to group them into chunks but skipping two elements after each chunk.

I have the code to divide the list into chunks:

chunk_size= 109
for i in range(0, len(ints), chunk_size):
    chunk = ints[i:i+chunk_size]

But how do I skip or delete two elements from the big list iteratively, ie, after attaining each chunk of size 109?

Is there a way to do that?

Add 2 to the chunk size when using it in the iteration.

chunk_size= 109
for i in range(0, len(ints), chunk_size+2):
    chunk = ints[i:i+chunk_size]

Use modular arithmetics:

blocksize = chuncksize + 2
newints = [i for i in ints if i%blocksize < chuncksize]

The other way is to loop backward:

blocksize = chuncksize + 2
for i in range(len(ints), 0, -blocksize)
    ints.pop(i+chuncksize)
    ints.pop(i+chuncksize+1)

Note: Did not test.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM