Let say there's a list X and another list num_items
that specify the number of items that should be in the sublist, I can split the list manually as such:
>>> x = list(range(10))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> num_items = [4, 4, 2]
>>> slice1 = x[:num_items[0]]
>>> slice2 = x[len(slice1):len(slice1)+num_items[1]]
>>> slice3 = x[len(slice1)+len(slice2):]
>>> slice1, slice2, slice3
([0, 1, 2, 3], [4, 5, 6, 7], [8, 9])
There will be two cases where the last few slices can become problematic, e.g. but that can be solved with the empty list given that I manually code the 3 slices:
>>> num_items = [9, 1, 1]
>>> slice1 = x[:num_items[0]]
>>> slice2 = x[len(slice1):len(slice1)+num_items[1]]
>>> slice3 = x[len(slice1)+len(slice2):]
>>> slice1, slice2, slice3
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9], [])
What if there are 4 slices, e.g.:
>>> num_items = [9, 1, 1, 2]
>>> slice1 = x[:num_items[0]]
>>> slice2 = x[len(slice1):len(slice1)+num_items[1]]
>>> slice3 = x[len(slice1)+len(slice2):len(slice1)+len(slice2)+num_items[2]]
>>> slice4 = x[len(slice1)+len(slice2)+len(slice3): len(slice)+len(slice2)+len(slice3)+num_items[3]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'type' has no len()
The desired output would be to add empty list to the 4th slice, i.e.:
>>> slice1, slice2, slice3, slice4
([0, 1, 2, 3, 4, 5, 6, 7, 8], [9], [], [])
If the num_items
requires lesser items than length of X, simply return until the sum of num_items
, i.e.
>>> num_items = [4, 4]
>>> slice1, slice2
([0, 1, 2, 3], [4, 5, 6, 7])
The main question is is there a way to split up the slices without manually coding the splits? (The answer to cover the case where the num_items
requests for more items than in X, in that case, empty sublists should be returned)
Keep in mind that the length of X can be rather big (i.e. > 10,000,000,000) but the length of num_items
ranges from 1 to 100 =)