Reputation: 93173
if i have :
def all=[11,12,12,13,13,13,14,15,16,10]
i want to split this list into 3 sublists that has almost the same size .
def result=[[11,12,12],[13,13,13],[14,15,16,10]]
i add a method to metaClass of List class : it is percent
metod:
See : https://stackoverflow.com/a/20005844/747579
So i can do :
def result=[all.percent(0,0.33),all.percent(0.34,0.66),all.percent(0.67,1)]
My question is : There is a method that splits a list into n sub-lists equisize , such as ;
def result=all.equisize(n) // n is the number of sublist wanted
Upvotes: 3
Views: 5814
Reputation: 171084
You could try:
def result = all.collate( all.size().intdiv( 3 ) )
Which gives:
assert result == [ [ 11, 12, 12 ], [ 13, 13, 13 ], [ 14, 15, 16 ], [ 10 ] ]
If you don't want to keep the spare [10]
at the end, you could pass false
to the keepRemainder
parameter of collate
:
def result = all.collate( all.size().intdiv( 3 ), false )
Upvotes: 14