Printing n elements per line in a list
Dan Sommers
me at privacy.net
Tue Aug 15 23:01:09 EDT 2006
On 15 Aug 2006 18:33:51 -0700,
"John Machin" <sjmachin at lexicon.net> wrote:
> Dan Sommers wrote:
>>
>> counter = 0
>> for an_element in the_list:
>> print an_element,
>> counter = counter + 1
>> if counter == n:
>> print
>> counter = 0
>>
> Yes, often simple old-fashioned ways are the best. A little verbose,
> though. And I'd do some old-fashioned testing -- the above needs "if
> counter: print" after the loop has finished, to get the final '\n' for
> cases where there are not an even multiple of n elements.
I know I *thought* "untested"; I could have sworn that I typed it, too.
Sorry.
OTOH, pasted directly from my interactive python session (I changed
sys.ps2 to four spaces to make pasting from these sessions into an
editor that much easier):
Python 2.4.2 (#1, Jun 17 2006, 00:09:19)
[GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> c = 0
>>> for e in range(10):
print e,
c = c + 1
if c == 3:
print
c = 0
0 1 2
3 4 5
6 7 8
9
>>>
And pasted right from an xterm:
$ python -c 'print 3,'
3
$
(All of which only explains your more complex test harness, and I still
should have looked more carefully before I posted.)
> ... ctr = (ctr + 1) % n
I'm old enough to remember the days when we avoided division like the
plague. Remember those zippy 1MHz (yes, that's an M and not a G) CPUs
with less than a handful of 8-bit registers? Old habits die hard. ;-)
Regards,
Dan
--
Dan Sommers
<http://www.tombstonezero.net/dan/>
"I wish people would die in alphabetical order." -- My wife, the genealogist
More information about the Python-list
mailing list