Nested lists or conditional logic?
Peter Otten
__peter__ at web.de
Wed Jan 28 14:19:31 EST 2004
mike beck wrote:
> this is not all complex, but as a noob i'm having a hard time getting
> my head around it.
>
> i have a list of items. i need to print the items in batches of x,
> with a summary line after each complete or partial batch, and a total
> line at the end of the job.
[...]
> i've done the following, which works, but it seems like there must be
> a better/simpler/faster way to do this with nested loops. ideas?
Your code looks OK to me (apart from the duplicate colon). Here's a "no
maths" variant that uses nested loops:
from itertools import islice
ITEMSINBATCH = 3;
ARBITRARYNUM = 11;
sample = ["item #%d" % i for i in range(ARBITRARYNUM)]
it = iter(sample)
while True:
more = False
for item in islice(it, ITEMSINBATCH):
more = True
print item
if not more: break
print "summary"
I'm generally fond of the itertools module; this time I didn't find a way to
get rid of the ugly more flag, though. Implementing your own iterator with
a hasMore() method seems overkill.
Peter
More information about the Python-list
mailing list