Grouping items attending to their distance from their average - Looping Issue

Hi there!

I’m new to coding and I have no idea how to solve this with ghpython (if there is also a clever way to do it with Grasshoper commands it is also welcome). I have some lines with different values assigned and their average and I would like to test the values of the lines so that when their value is larger than the average they remain alone, but when it is smaller they add their value to the next one and test again if it is smaller than the average. If it is they do the same opperation again and if not the same process starts with the next value. I have tried with a while loop but it exits it every time the condition is fulfilled and with recursion but honestly I have no idea what I’m doing.

val1 < average
yes
val1 + val2 < average
no
group val1 and val2 and start the same process with val3

I attach an image that makes it easier to understand.

Thanks a lot for the help and your time!