Nested lists or conditional logic?
Joe Francia
usenet at -OBFUSCATION-joefrancia.com
Wed Jan 28 13:41:34 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.
>
> if the list looks like ['line1','line2','line3'], and my ITEMSINBATCH
> = 1, the output should look like this:
>
> line1
> ---summary line---
> line2
> ---summary line---
> line3
> ---summary line---
> ---total line---
>
> if ITEMSINBATCH = 2, the output should look like this:
>
> line1
> line2
> ---summary line---
> line3
> ---summary line---
> ---total line---
>
> 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?
>
>
> # ---------------------Begin code---------------------
> ITEMSINBATCH = 1;
> ARBITRARYNUM = 51;
>
> # create a list to work with
> myList = ['1']*ARBITRARYNUM;
>
> for i in range( len(myList) ):
> # avoid starting at 0
> count = i + 1;
>
> print "The item is:",myList[i],'\t',count;
>
> # ensure that the batch summary line is printed every ITEMSINBATCH
> # times but not if the number of items is evenly divisible by
> # ITEMSINBATCH, in which case both the inner print and the outer
> # print would execute and we'd get consecutive batch summary lines
> if ( (count) % ITEMSINBATCH ) is 0 and count != len(myList)::
> print "-----Add batch summary line-----";
>
> # add a final batch line for those trailing items
> print "------Add batch summary line------And BTW, i is", count;
>
> # and add the final summary line
> print "------Add file summary------";
>
> # ---------------------End code---------------------
I'm not sure this is faster, but it sure is simpler:
mylist = range(23)
batchsize = 4
for i in range(0,len(mylist),batchsize):
for l in mylist[i:i+batchsize]:
print l
print "---summary line---"
print "---file summary---"
--
Soraia: http://www.soraia.com
More information about the Python-list
mailing list