Breaking Python list into set-length list of lists

MRAB google at mrabarnett.plus.com
Thu Feb 12 17:12:11 CET 2009


Mensanator wrote:
> On Feb 11, 10:58�pm, Jason <elgrandchig... at gmail.com> wrote:
>> Hey everyone--
>>
>> I'm pretty new to Python, & I need to do something that's incredibly
>> simple, but combing my Python Cookbook & googling hasn't helped me out
>> too much yet, and my brain is very, very tired & flaccid @ the
>> moment....
>>
>> I have a list of objects, simply called "list". �I need to break it
>> into an array (list of lists) wherein each sublist is the length of
>> the variable "items_per_page". �So array[0] would go from array[0][0]
>> to array[0][items_per_page], then bump up to array[1][0] - array[1]
>> [items_per_page], until all the items in the original list were
>> accounted for.
>>
>> What would be the simplest way to do this in Python? �And yes, I
>> realize I should probably be taking Programming 101.....
> 
>>>> items_per_page = 20
>>>> x = range(113)
>>>> layout = divmod(113,20)
>>>> if layout[1]>0:
> 	pages = layout[0]+1
> else:
> 	pages = layout[0]
>>>> array = [ x[i*items_per_page:i*items_per_page+items_per_page]  for i in xrange(pages)]
>>>> array
> [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
> 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
> 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
> 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
> 70, 71, 72, 73, 74, 75, 76, 77, 78, 79], [80, 81, 82, 83, 84, 85, 86,
> 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], [100, 101, 102,
> 103, 104, 105, 106, 107, 108, 109, 110, 111, 112]]
 >
Using list comprehension:

 >>> my_list = range(113)
 >>> items_per_page = 20
 >>>
 >>> array = [my_list[start : start + items_per_page] for start in 
range(0, len(my_list), items_per_page)]
 >>>
 >>> array
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19], 
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 
38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 
55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 
72, 73, 74, 75, 76, 77, 78, 79], [80, 81, 82, 83, 84, 85, 86, 87, 88, 
89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], [100, 101, 102, 103, 104, 
105, 106, 107, 108, 109, 110, 111, 112]]
 >>>



More information about the Python-list mailing list