Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print python list in groups of 3

I have a list of 107 names, I would like to print them out in groups of 3 or so, with each name separated by a tab, a newline after each line, until the end. How can I do this?

with for item in list print item i only get 1 name per line of course, which is fine I guess but i'd like to fit more in the console at once so I'd like to print 3 or so names on each line as I go through the list, so instead of:

name1
name2
name3
name4
name5
name6

i would get:

name1     name2     name3
name4     name5     name6

It's kindof hard to search for an answer to this, i haven't been able to come up with quite what I need or that I could understand, most things I did find just deal with len() or range() and confused me. Is there some simple way to do this? Thank you!

[edit:update] using @inspectorG4dget's example of:

for i in range(0, len(listnames), 5):
    print '\t\t'.join(listnames[i:i+5])

i get the following: http://www.pasteall.org/pic/show.php?id=41159

how can I get that cleaned up so everything is nicely aligned in each column? Is what I want possible to do easily?

like image 924
Kassandra Avatar asked Feb 21 '26 02:02

Kassandra


1 Answers

1)

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'ii','uuuuuuuuuuuuuuuuuuu','aaa',
      'round','flat','sharp',
      'blueberry','banana','apple',
      'red','purple','white',
      'hen','tiger']

a,b = divmod(len(li),3)
itn = iter(li).next
print ''.join('%s\t%s\t%s\n' % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%s\t%s\t\n' % (itn(),itn()) if b==2
         else '%s\t\n' % itn() if b==1
         else '')

result

sea mountain    desert
Emma    Cathy   Kate
ii  uuuuuuuuuuuuuuuuuuu aaa
round   flat    sharp
blueberry   banana  apple
red purple  white
hen tiger   

.

2)

And to align in columns whose width depends on the longest element of the list:

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'blueberry','banana','apple',
      'red','purple','white',
      'hen','tiger']

maxel = max(len(el) for el in li)
a,b = divmod(len(li),3)
itn = iter(li).next
form = '%%-%ds\t%%-%ds\t%%-%ds\n' % (maxel,maxel,maxel)
print ''.join(form % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%%-%ds\t%%-%ds\t\n' %(maxel,maxel) % (itn(),itn()) if b==2
         else '%%-%ds\t\n' % ma% itn() if b==1
         else '')

result

sea         mountain    desert   
Emma        Cathy       Kate     
HH          VVVVVVV     AAA      
round       flat        sharp    
blueberry   banana      apple    
red         purple      white    
hen         tiger       

.

3)

To align in column, the width of each column depending upon the longest element in it:

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'red','purple','white',
      'hen','tiger']

maxel0 = max(len(li[i]) for i in xrange(0,len(li),3)) 
maxel1 = max(len(li[i]) for i in xrange(1,len(li),3))
maxel2 = max(len(li[i]) for i in xrange(2,len(li),3))
a,b = divmod(len(li),3)
itn = iter(li).next
form = '%%-%ds\t%%-%ds\t%%-%ds\n' % (maxel0,maxel1,maxel2)
print ''.join(form % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%%-%ds\t%%-%ds\t\n' %(maxel0,maxel1) % (itn(),itn()) if b==2
         else '%%-%ds\t\n' % maxel0 % itn() if b==1
         else '')

result

sea     mountain    desert
Emma    Cathy       Kate  
HH      VVVVVVV     AAA   
round   flat        sharp 
nut     banana      apple 
red     purple      white 
hen     tiger       

4)

I've modified the algorithm in order to generalize to any number of columns wanted.
The wanted number of columns must be passed as argument to parameter nc :

from itertools import imap,islice

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'heeeeeeeeeeen','tiger','snake'
      'red','purple','white',
      'atlantic','pacific','antarctic',
      'Bellini']

print 'len of li == %d\n' % len(li)

def cols_print(li,nc):
    maxel = tuple(max(imap(len,islice(li,st,None,nc)))
                  for st in xrange(nc))

    nblines,tail = divmod(len(li),nc)
    stakes = (nc-1)*['%%-%ds\t'] + ['%%-%ds']
    form = ''.join(stakes) % maxel

    itn = iter(li).next

    print '\n'.join(form % tuple(itn() for g in xrange(nc))
                  for i in xrange(nblines)) 
    if tail:
        print ''.join(stakes[nc-tail:]) % maxel[0:tail] % tuple(li[-tail:]) + '\n'
    else:
        print


for nc in xrange(3,8):
    cols_print(li,nc)
    print '-----------------------------------------------------------'

result

len of li == 24

sea             mountain    desert  
Emma            Cathy       Kate    
HH              VVVVVVV     AAA     
round           flat        sharp   
nut             banana      apple   
heeeeeeeeeeen   tiger       snakered
purple          white       atlantic
pacific         antarctic   Bellini 

-----------------------------------------------------------
sea         mountain    desert      Emma         
Cathy       Kate        HH          VVVVVVV      
AAA         round       flat        sharp        
nut         banana      apple       heeeeeeeeeeen
tiger       snakered    purple      white        
atlantic    pacific     antarctic   Bellini      

-----------------------------------------------------------
sea             mountain    desert      Emma    Cathy
Kate            HH          VVVVVVV     AAA     round
flat            sharp       nut         banana  apple
heeeeeeeeeeen   tiger       snakered    purple  white
atlantic        pacific     antarctic   Bellini

-----------------------------------------------------------
sea     mountain    desert      Emma            Cathy       Kate    
HH      VVVVVVV     AAA         round           flat        sharp   
nut     banana      apple       heeeeeeeeeeen   tiger       snakered
purple  white       atlantic    pacific         antarctic   Bellini 

-----------------------------------------------------------
sea     mountain        desert  Emma        Cathy   Kate    HH      
VVVVVVV AAA             round   flat        sharp   nut     banana  
apple   heeeeeeeeeeen   tiger   snakered    purple  white   atlantic
pacific antarctic       Bellini

-----------------------------------------------------------

.

But I prefer a displaying in which there are no tabs between columns, but only a given number of characters.
In the following code, I choosed to separate the columns by 2 characters: it is the 2 in the line

maxel = tuple(max(imap(len,islice(li,st,None,nc)))+2

The code

from itertools import imap,islice

li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'heeeeeeeeeeen','tiger','snake'
      'red','purple','white',
      'atlantic','pacific','antarctic',
      'Bellini']

print 'len of li == %d\n' % len(li)
def cols_print(li,nc):
    maxel = tuple(max(imap(len,islice(li,st,None,nc)))+2
                  for st in xrange(nc))

    nblines,tail = divmod(len(li),nc)
    stakes = nc*['%%-%ds']
    form = ''.join(stakes) % maxel

    itn = iter(li).next

    print '\n'.join(form % tuple(itn() for g in xrange(nc))
                  for i in xrange(nblines)) 
    if tail:
        print ''.join(stakes[nc-tail:]) % maxel[0:tail] % tuple(li[-tail:]) + '\n'
    else:
        print


for nc in xrange(3,8):
    cols_print(li,nc)
    print 'mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm'

the result

len of li == 24

sea            mountain   desert    
Emma           Cathy      Kate      
HH             VVVVVVV    AAA       
round          flat       sharp     
nut            banana     apple     
heeeeeeeeeeen  tiger      snakered  
purple         white      atlantic  
pacific        antarctic  Bellini   

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea       mountain  desert     Emma           
Cathy     Kate      HH         VVVVVVV        
AAA       round     flat       sharp          
nut       banana    apple      heeeeeeeeeeen  
tiger     snakered  purple     white          
atlantic  pacific   antarctic  Bellini        

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea            mountain  desert     Emma     Cathy  
Kate           HH        VVVVVVV    AAA      round  
flat           sharp     nut        banana   apple  
heeeeeeeeeeen  tiger     snakered   purple   white  
atlantic       pacific   antarctic  Bellini  

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea     mountain  desert    Emma           Cathy      Kate      
HH      VVVVVVV   AAA       round          flat       sharp     
nut     banana    apple     heeeeeeeeeeen  tiger      snakered  
purple  white     atlantic  pacific        antarctic  Bellini   

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
sea      mountain       desert   Emma      Cathy   Kate   HH        
VVVVVVV  AAA            round    flat      sharp   nut    banana    
apple    heeeeeeeeeeen  tiger    snakered  purple  white  atlantic  
pacific  antarctic      Bellini  

mwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwmwm
like image 178
eyquem Avatar answered Feb 22 '26 15:02

eyquem