Search code examples
pythonlistrangeslicechunks

How to Slice List as bytes range Chunk?


I have total Size for example 1037

and chunk size for example 50

i want a list contain range such as:

['0 - 50' , '50 - 100' , '100 - 150' , ....]

to end (1037)

how to do this Please ?

i try use:

n = 1037


chunk_size = 50
x = [f'{sa} - {sa + chunk_size }' for sa in range(0, (n - (n % chunk_size)), chunk_size+1)] + [f'{(n // chunk_size) * chunk_size } - {n}' if ((n // chunk_size) * chunk_size ) < n else '']
print(x)

I got:

['0 - 50', '51 - 101', '102 - 152', '153 - 203', '204 - 254', '255 - 305', '306 - 356', '357 - 407', '408 - 458', '459 - 509', '510 - 560', '561 - 611', '612 - 662', '663 - 713', '714 - 764', '765 - 815', '816 - 866', '867 - 917', '918 - 968', '969 - 1019', '1000 - 1037'] 

but after 1019 should be '1020 - 1037'


Solution

  • You have one less for each chunk you calculated for the last pair. Just add them back. see the int(n / chunk_size) below.

    x = [f'{sa} - {sa + chunk_size }' for sa in range(0, (n - (n % chunk_size)), chunk_size+1)] + [f'{(n // chunk_size) * chunk_size + int(n / chunk_size)} - {n}' if ((n // chunk_size) * chunk_size ) < n else '']