I know how to split a list into even groups, but I'm having trouble splitting it into uneven groups.
Essentially here is what I have: some list, let's call it mylist
, that contains x elements.
I also have another file, lets call it second_list, that looks something like this:
{2, 4, 5, 9, etc.}
Now what I want to do is divide mylist
into uneven groups by the spacing in second_list. So, I want my first group to be the first 2 elements of mylist
, the second group to be the next 4 elements of mylist
, the third group to be the next 5 elements of mylist
, the fourth group to be the next 9 elements of `mylist, and so on.
Is there some easy way to do this? I tried doing something similar to if you want to split it into even groups:
for j in range(0, len(second_list)):
for i in range(0, len(mylist), second_list[j]):
chunk_mylist = mylist[i:i+second_list[j]]
However this doesn't split it like I want it to. I want to end up with my # of sublists being len(second_list)
, and also split correctly, and this gives a lot more than that (and also splits incorrectly).
Using list-comprehensions together with slicing and
sum()
function (all basic and built-in tools of python):If
seclist
is very long and you wish to be more efficient usenumpy.cumsum()
first:and get the same results
At the end
subgroups
will contain the desired listsExample run:
A numpythonic approach:
And here is a Python3.X approach using
itertool.accumulate()
:This solution keeps track of how many items you've written. It will crash if the sum of the numbers in the
second_list
is longer thanmylist
After running this,
listChunks
is a list containing sublists with the lengths found insecond_list
.Padriac has the best solution IMO, but I'll chime in with this hacky one liner that requires no imports:
You can create an iterator and itertools.islice:
Which would give you:
Once i elements are consumed they are gone so we keep getting the next i elements.
Not sure what should happen with any remaining elements, if you want them added, you could add something like:
Which would give you:
Or in contrast if there were not enough, you could use a couple of approaches to remove empty lists, one an inner generator expression:
Or combine with itertools.takewhile:
Which for:
would give you:
As opposed to:
What you use completely depends on your possible inouts and how you would like to handle the various possibilities.