I asked this last night but poorly worded it on my part. I'm trying to take a list of:
['milk','eggs','beef','oranges','dog food','chips','soda','bread']
And split it into lists of n each, any remainders need to be added evenly to the lists.. so the outcome would be for n = 3:
[['milk','eggs','beef'],['oranges','dog food','chips']]
With a remainder of: ['soda','bread'] that would give me the final result of:
[['milk','eggs','beef','soda'],['oranges','dog food','chips','bread']]
Order doesn't matter.
A short but efficient solution:
def splitList (lst, n):
it = iter(lst)
new = [[next(it) for _ in range(n)] for _ in range(len(lst) // n)]
for i, x in enumerate(it):
new[i].append(x)
return new
>>> lst = ['milk', 'eggs', 'beef', 'oranges', 'dog food', 'chips', 'soda', 'bread']
>>> splitList(lst, 3)
[['milk', 'eggs', 'beef', 'soda'], ['oranges', 'dog food', 'chips', 'bread']]
>>> splitList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3)
[[1, 2, 3, 10], [4, 5, 6], [7, 8, 9]]
This first creates a single iterator which we use for everything; so in total we only loop once over the list. The number of sublists that will be created is len(lst) // n (integer division rounds down), and for each sublist we take n values from the iterator.
After that, the remaining items will be still left in the iterator, so we can simply iterate over the rest of them and append them to the sublists directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With