pythonlistindexingchunks

Split lists into chunk based of index of another list


I want to split a list into chunks using values of of another list as the range to split.

indices = [3, 5, 9, 13, 18]
my_list = ['a', 'b', 'c', ..., 'x', 'y', 'z']

So basically, split my_list from range:

my_list[:3], mylist[3:5], my_list[5:9], my_list[9:13], my_list[13:18], my_list[18:]

I have tried to indices into chunks of 2 but the result is not what i need.

[indices[i:i + 2] for i in range(0, len(indices), 2)]

My actual list length is 1000.


Solution

  • You could also do it using simple python.

    Data

    indices = [3, 5, 9, 13, 18]
    my_list = list('abcdefghijklmnopqrstuvwxyz')
    

    Solution

    Use list comprehension.

    [(my_list+[''])[slice(ix,iy)] for ix, iy in zip([0]+indices, indices+[-1])]
    

    Output

    [['a', 'b', 'c'],
     ['d', 'e'],
     ['f', 'g', 'h', 'i'],
     ['j', 'k', 'l', 'm'],
     ['n', 'o', 'p', 'q', 'r'],
     ['s', 't', 'u', 'v', 'w', 'x', 'y', 'z']]
    

    Check if correct order of indices are extracted

    dict(((ix,iy), (my_list+[''])[slice(ix,iy)]) for ix, iy in zip([0]+indices, indices+[-1]))
    

    Output

    {(0, 3): ['a', 'b', 'c'],
     (3, 5): ['d', 'e'],
     (5, 9): ['f', 'g', 'h', 'i'],
     (9, 13): ['j', 'k', 'l', 'm'],
     (13, 18): ['n', 'o', 'p', 'q', 'r'],
     (18, -1): ['s', 't', 'u', 'v', 'w', 'x', 'y', 'z']}