On Jan 13, 2:02 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > thebjorn wrote: > > > Eh... > > oh, forgot that it was "pulling requirements out of thin air" week on > c.l.python.
Well, the OP requirements were to control the number of chunks, not the size of them, so I guess we both got it wrong initially. > > def chop(lst, length): > > n = len(lst) / length > > z = [lst[i:i+n] for i in xrange(0, len(lst), n)] > > if len(z[-1]) < n and len(z) > 1: > > z[-2].extend(z.pop(-1)) > > return z > > > gives > >>>> chop([1], 3) > > Traceback (most recent call last): > > File "<stdin>", line 1, in <module> > > File "beforemeth.py", line 9, in chop > > if len(z[-1]) < n and len(z) > 1: > > ValueError: xrange() arg 3 must not be zero > > well, it doesn't. there's no xrange on that line. It's from this line z = [lst[i:i+n] for i in xrange(0, len(lst), n)] (I executed the file with python -i beforemeth.py to get to an interactive prompt, I'm sure you're familiar with the technique. You could have just debugged your own program to find it though, or just looked at the code -- not that many xrange calls in there, eh?) > > Perhaps something like this? > > > from itertools import islice > > or just use an if-statement, or the max function. but I guess those > tools are too old and boring for c.l.python these days... I didn't realize correct code was too new-school. Perhaps you should publish a list of modules you don't like, or perhaps I should just use a sufficiently venerable version of Python? Ok, here you go: C:\Python22>python 'import site' failed; use -v for traceback Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def chop2(lst, nchunks): ... chunksize = len(lst) // nchunks ... if not chunksize: ... raise ValueError('More chunks than elements in list.') ... res = [] ... begin, end = 0, chunksize ... for i in range(nchunks-1): ... res.append(lst[begin:end]) ... begin, end = end, end+chunksize ... res.append(lst[begin:]) ... return res ... >>> chop2(range(1,6), 2) [[1, 2], [3, 4, 5]] >>> chop2(range(1,6), 3) [[1], [2], [3, 4, 5]] >>> chop2(range(1,11), 3) [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]] >>> Sufficiently old-school (or do I need to take out the // division also?) > </F> Shall we perhaps drop some of the attitude? (you used to be so much nicer before you wrote sre ;-) -- bjorn -- http://mail.python.org/mailman/listinfo/python-list