Create sublists knowing the lengths of each list

Viewed 40

I'm having some trouble trying to create this.

I have the following lists:

values = [(3, 50), (4, 20), (10, 30), (11, 60), (12, 70), (13, 20)]
lens = [2,4]

What I want to do is to generate another list of sublists knowing the exact length of each sublist, so the output would be this one:

result = [[(3, 50), (4, 20)], [(10, 30), (11, 60), (12, 70), (13, 20)]]

Thank you very much!

2 Answers

You could create an iterator out of values and call next on it in a list comprehension:

iterator = iter(values)
result = [[next(iterator) for _ in range(length)] for length in lens]

Here are two possible approaches.

A more 'basic' one, managing indices 'by hand':

values = [(3, 50), (4, 20), (10, 30), (11, 60), (12, 70), (13, 20)]
lens = [2,4]

def slices1(values, lens):
    out = []
    index = 0
    for length in lens:
        out.append(values[index:index+length])
        index += length
    return out

print(slices1(values, lens))
# [[(3, 50), (4, 20)], [(10, 30), (11, 60), (12, 70), (13, 20)]]

Another one, using an iterator on the list, and itertools.islice to get successive slices from it:

from itertools import islice

def slices2(values, lens):
    it = iter(values)
    out = [list(islice(it,length)) for length in lens]
    return out

print(slices2(values, lens))
# [[(3, 50), (4, 20)], [(10, 30), (11, 60), (12, 70), (13, 20)]]
Related