better way to write this function
Peter Otten
__peter__ at web.de
Tue Nov 27 02:39:47 EST 2007
Ricardo Aráoz wrote:
> Peter Otten wrote:
>> You can use slicing:
>>
>>>>> def chunks(items, n):
>> ... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
>> ...
>>>>> for i in range(1,10):
>> ... print chunks(range(5), i)
>> ...
>> [[0], [1], [2], [3], [4]]
>> [[0, 1], [2, 3]]
>> [[0, 1, 2]]
>> [[0, 1, 2, 3]]
>> [[0, 1, 2, 3, 4]]
>> []
>> []
>> []
>> []
>
>
> This won't work(e.g. you don't define "start", you change the value of n
> through the loop). I guess you meant :
>
> def chunks(items, n) :
> return [items[i:i+n] for i in range(0, len(items)-n+1, n)]
Indeed; I'm still wondering how I managed to copy'n'paste the version with
the typo together with the demo of the correct one.
Peter
More information about the Python-list
mailing list