Printing n elements per line in a list
Simon Forman
rogue_pedro at yahoo.com
Tue Aug 15 22:58:43 EDT 2006
John Machin wrote:
> Steven D'Aprano wrote:
> > I think it's possible to
> > > hack it up using while loops and some ugly slicing, but hopefully I'm
> > > missing something
> >
> > I don't see why you think that's an ugly hack.
> >
> > def printitems(sequence, count=5):
> > """Print count items of sequence per line."""
> > numrows = len(sequence)//count
> > if len(sequence)%count != 0: numrows += 1
> > for start in range(0, numrows):
> > items = sequence[start*count:(start+1)*count]
> > for item in items:
> > print item,
> > print
>
> Ugliness is in the eye of the beholder.
> It is more blessed to add than to multiply.
> Gaze upon this alternative:
>
> def printitems2(sequence, count=5):
> """Print count items of sequence per line."""
> for pos in range(0, len(sequence), count):
> for item in sequence[pos:pos+count]:
> print item,
> print
>
> Cheers,
> John
Very nice.
~Simon
More information about the Python-list
mailing list