Simple List division problem

Pierre Quentel quentel.pierre at wanadoo.fr
Mon Jan 14 16:05:28 EST 2008


On 12 jan, 19:37, marcstuart <marc.stuart.ris... at gmail.com> wrote:
> How do I divide a list into a set group of sublist's- if the list is
> not evenly dividable ?
> consider this example:
>
> x = [1,2,3,4,5,6,7,8,9,10]
> y = 3      # number of lists I want to break x into
> z = y/x
>
> what I would like to get is 3 sublists
>
> print z[0] = [1,2,3]
> print z[2] = [4,5,6]
> print z[3] = [7,8,9,10]
>
> obviously not even, one list will have 4 elements, the other 2 will
> have 3.,
> the overriding logic, is that I will get 3 lists and find a way for
> python to try to break it evenly, if not one list can have a greater
> amount of elements
>
> Would I use itertools ? How would I do this ?
>
> Thanks

Hi,

If you want to split the list in 4, do you want
[1,2],[3,4],[5,6],[7,8,9,10] : all extra items in the last sublist
or
[1,2],[3,4],[5,6,7],[8,9,10] : one extra item in each of the last
sublists ?

Assuming you want the second version :

=======================
def split_list(lst,nb):
    # ln = length of smaller sublists
    # extra = number of longer sublists (they have ln+1 items)
    ln,extra = divmod(len(lst),nb)
    pos = ln*(nb-extra) # position where larger sublists begin
    return [ lst[i*ln:(i+1)*ln] for i in xrange(nb-extra) ] \
        + [lst[pos+i*(ln+1):pos+(i+1)*(ln+1)] for i in xrange(extra)]

======================

x = range(1,11)

print split_list(x,1)
>>>[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
print split_list(x,2)
>>>[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
print split_list(x,3)
>>>[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
print split_list(x,4)
>>>[[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]]
print split_list(x,5)
>>>[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
print split_list(x,10)
>>>[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]



More information about the Python-list mailing list