0

I start with a long list, long let's say 4438. I need to create a list of sublists of that starting list. To do that, I have a list of indexes:

indexes = [0, 888, 1776, 2664, 3551, 4438]

This means, in my final list, the first sublist takes the first 888 elements, the second one the following 888, the third one the following 888 and so on.

What I need is the sublists to be:

sublist_1 = list_to_slice[0:888]
sublist_2 = list_to_slice[888:1776]
sublist_3 = list_to_slice[1776:2664]
...

My code:

final_list = [list_to_slice[i:i+1] for i in indexes]

The problem with my code is that instead of doing the above slicing, it does:

sublist_1 = list_to_slice[0:1]
sublist_2 = list_to_slice[888:889]
sublist_3 = list_to_slice[1776:1777]
...

That i+1 is deemed 'add 1 to the index i' instead of 'take the index that follows i', how can I get the code to do the latter? I need a fine piece of code that does this kind of slicing, I don't care if different to mine.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Riccardo Lamera
  • 105
  • 1
  • 13
  • Iterate the list in blocks. For example: `[indexes[i:i+10] for i in indexes[::10]]`. – S3DEV Apr 27 '22 at 12:50
  • You could change your code so that it will use `indexes[i]` and `indexes[i+1]` instead of `i` and `i+1`. Of course, this requires to generate `i` differently. – mkrieger1 Apr 27 '22 at 12:53

1 Answers1

2

Using itertools.pairwise:

>>> from itertools import pairwise
>>> for i, j in pairwise([0, 888, 1776, 2664, 3551, 4438]):
...     print(i, j)
...
0 888
888 1776
1776 2664
2664 3551
3551 4438

What's next? I think you can solve it yourself.

Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31