vendredi 5 mars 2021

Split a list randomly given chunk sizes in python

I want to write a function that returns a list of randomly splitted chunks, given a list of sizes of each chunk. For example, say I have a list of unique integers from 0 to 9

lst = list(range(10))

I want to split into 4 chunks of sizes 1, 2, 2 and 5, so the function should take an input variable sizes as below:

my_func(lst, sizes=[1, 2, 2, 5])

I expect the function to return something like

[[3], [1, 7], [2, 4], [0, 5, 6, 8, 9]]

If the input sizes = [5, 1, 4], I expect the function to return something in order like

[[1, 3, 4, 6, 8], [9], [0, 2, 5, 7]]

Any suggestions?




Aucun commentaire:

Enregistrer un commentaire