Simple List division problem

Gary Herron gherron at islandtraining.com
Sat Jan 12 14:31:56 EST 2008


marcstuart 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
>   

Calculate the size of a normal sublist, and the amount of extra that
goes with the last sublist.
Then extract y-1 normal sized sublists and one possibly larger sublist.

>>> x = [1,2,3,4,5,6,7,8,9,10]
>>> y = 3
>>> s = len(x)/y
>>> s                        # size of normal sublists
3
>>> e = len(x) - y*s  # extra elements for last sublist
>>> e
1
>>> z = [x[s*i:s*i+s] for i in range(y-1)] + [x[-s-e:]] #extract y-1
normal + 1 larger sublists
>>> z
[[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]

Done!

Gary Herron








More information about the Python-list mailing list