473,788 Members | 2,893 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Printing n elements per line in a list

If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something

Aug 15 '06
26 17962
def perline(n):
count = 1
while 1:
yield (count == n) and "\n" or " "
count = count % n + 1

r = range(1,101)
p = perline(5)

print "".join("%d %s" % (x, p.next()) for x in r)

unexpected wrote:
If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print all the
values of the list on a single line, but that's not what I want. I feel
like there is an easy, pretty way to do this. I think it's possible to
hack it up using while loops and some ugly slicing, but hopefully I'm
missing something
Aug 17 '06 #21

Matimus wrote:
Well, I have another at bat, so I will try to redeem myself... using
recursion:

def printTable(l,c) :
print(("%d "*len(l[:c]))%tuple(l[:c]))
if( len(l[:c]) 0 ):
printTable(l[c:],c)

printTable(rang e(1,101),5)
Sorry. Recursion disqualified your batter before he got out of the
dugout. Besides the %d restricts it to use wirh integers, and using
"L".lower() as a variable name made the umpire barf through his
facemask all over the catcher. Fortunately the ump didn't notice the
weirdly-spaced and superfluous () in the if statement ...

Aug 17 '06 #22
On 2006-08-15, unexpected <su***********@ gmail.comwrote:
If have a list from 1 to 100, what's the easiest, most elegant
way to print them out, so that there are only n elements per
line.

So if n=5, the printed list would look like:

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc.

My search through the previous posts yields methods to print
all the values of the list on a single line, but that's not
what I want. I feel like there is an easy, pretty way to do
this. I think it's possible to hack it up using while loops and
some ugly slicing, but hopefully I'm missing something
I can't resist putting in my oar:

def print_per(seq, n, isep=" ", rsep="\n"):
"""Print the items in seq, splitting into records of length n.

Trailing records may be shorter than length n."""
t = len(seq)
for i in xrange(n, t+1, n):
print isep.join(map(s tr, seq[i-n:i]))+rsep,
t = t % n
if t 0:
print isep.join(map(s tr, seq[-t:]))+rsep,

That's probably similar to some of the other mostly
non-functional solutions posted.

--
Neil Cerutti
Aug 17 '06 #23
unexpected wrote:
If have a list from 1 to 100, what's the easiest, most elegant way to
print them out, so that there are only n elements per line.
I've run into this problem a few times, and although many solutions
have been presented specifically for printing I would like to present a
more general alternative.

from itertools import chain
def istepline(step, iterator):
i = 0
while i < step:
yield iterator.next()
i += 1

def istep(iterable, step):
iterator = iter(iterable) # Make sure we won't restart iteration
while True:
# We rely on istepline()'s side-effect of progressing the
# iterator.
start = iterator.next()
rest = istepline(step - 1, iterator)
yield chain((start,), rest)
for i in rest:
pass # Exhaust rest to make sure the iterator has
# progressed properly.
>>i = istep(range(12) , 5)
for x in i: print list(x)
....
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11]
>>i = istep(range(12) , 5)
for x in i: print x
....
<itertools.chai n object at 0xa7d3268c>
<itertools.chai n object at 0xa7d3260c>
<itertools.chai n object at 0xa7d3266c>
>>from itertools import islice, chain, repeat
def pad(iterable, n, pad): return islice(chain(it erable, repeat(pad)), n)
i = istep(range(12) , 5)
for x in i: print list(pad(x, 5, None))
....
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, None, None, None]

Would anybody else find this useful? Maybe worth adding it to itertool?

Aug 19 '06 #24
Rhamphoryncus wrote:
I've run into this problem a few times, and although many solutions
have been presented specifically for printing I would like to present a
more general alternative.
[snip interesting istep function]
Would anybody else find this useful? Maybe worth adding it to itertool?
yeah, but why on earth did you make it so complicated?

def istep(iterable, step):
a=[]
for x in iterable:
if len(a) >= step:
yield a
a=[]
a.append(x)
if a:
yield a

--
- Justin

Aug 21 '06 #25
In <11************ *********@p79g2 000cwp.googlegr oups.com>, Justin Azoff
wrote:
Rhamphoryncus wrote:
[snip interesting istep function]
>Would anybody else find this useful? Maybe worth adding it to itertool?

yeah, but why on earth did you make it so complicated?

def istep(iterable, step):
a=[]
for x in iterable:
if len(a) >= step:
yield a
a=[]
a.append(x)
if a:
yield a
This is not as "lazy" as Rhamphoryncus' function anymore. Lets say the
`iterable` is a stream of events, then your function always needs to
"receive" `step` events before the caller can do anything else with the
events. In Rhamphoryncus' function the caller can react on the event as
soon as it's "delivered" by `iterable`.

Ciao,
Marc 'BlackJack' Rintsch
Aug 21 '06 #26
On 2006-08-19, Rhamphoryncus <rh****@gmail.c omwrote:
unexpected wrote:
>If have a list from 1 to 100, what's the easiest, most elegant
way to print them out, so that there are only n elements per
line.

I've run into this problem a few times, and although many
solutions have been presented specifically for printing I would
like to present a more general alternative.

from itertools import chain
def istepline(step, iterator):
i = 0
while i < step:
yield iterator.next()
i += 1

def istep(iterable, step):
iterator = iter(iterable) # Make sure we won't restart iteration
while True:
# We rely on istepline()'s side-effect of progressing the
# iterator.
start = iterator.next()
rest = istepline(step - 1, iterator)
yield chain((start,), rest)
for i in rest:
pass # Exhaust rest to make sure the iterator has
# progressed properly.

Would anybody else find this useful? Maybe worth adding it to
itertool?
Your note me curious enough to re-read the itertools
documentation, and I found the following in 5.16.3 Recipes:

def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip(*[chain(iterable, repeat(padvalue , n-1))]*n)

Wish I'd found that yesterday. ;)

--
Neil Cerutti
Aug 21 '06 #27

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1881
by: beliavsky | last post by:
To print a list with a specified format one can write (for example) for j in : print "%6d"%j, print The code print "%6d"%
12
6741
by: Stanimir Stamenkov | last post by:
Here are two cases regarding inline-level elements' line-height, padding and background, which I doesn't understand: <div style="background: black; color: white; line-height: 1.5"> <span>Abc</span> <span style="background: white; color: black; line-height: 3">Abc</span> <span>Abc</span> </div>
12
2331
by: Tescobar | last post by:
Over one year ago somebody asked here: how to remove selected elements from list in a loop?. The answer was as follows: for( it = l.begin(); it != l.end; ) { if(...) it = l.erase(it); else ++it;
5
1813
by: micklee74 | last post by:
hi i have a list with contents like this alist = how can i "convert" this list into a dictionary such that dictionary = { '>QWER':'askfhs' , '>REWR' : 'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' }
13
2087
by: cz | last post by:
Hi there, I'm sure there is a very simple solution for my question, I just didn't find it up to now. I'm using a badly documented module and therefore need to find out about how to access the elements in a list. (I need to do this in Python 1.5.3) Any help appreciated very much. Thanks! cz
3
2987
by: Muhammad Ahsin Saleem | last post by:
Hi I want to make a multi Line List Box. This list box will have multiple lines for one item and this list box have all other functions like the single line list box. Can any body help me its urgant
6
10375
by: Tekkaman | last post by:
I have a list of lists and I want to define an iterator (let's call that uniter) over all unique elements, in any order. For example, calling: sorted(uniter(, , ])) must return . I tried the following implementations: from itertools import chain
4
3178
by: Bob | last post by:
Is there a faster way to add the array elements to a list then looping through the elements like: double toadd; list<doublelistwant; for (int i=0;i<toadd.Length;i++){ listwant.Add(toadd);
11
28519
by: patelxxx | last post by:
When I running the following .cgi script, not sure why each print statement is not printing on a new line, even after entering \n. Browser=IE6 See Perl code below: #!C:/perl/bin/perl.exe -w print "Content-type:text/html\n\n"; use CGI qw(:standard);
2
3277
by: antar2 | last post by:
Hello, I am a beginner in python. following program prints the second element in list of lists 4 for the first elements in list 4 that are common with the elements in list 5 list4 = ,,] list5 =
0
9656
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10366
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10173
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4070
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3674
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.