1

I am new to python and was going through a problem. I have a text file which I read into a list and then divide it into chunks or "teams". The number of sub lists are created based on the number of teams I want. All this is done. But I want to print it out in a nice tabular format. Ive looked into the following questions this, this and this, but they are not what I ma looking for. Ive even looked at pypi modules PrettyTable and DataGrid.

My final list looks like this:

['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]

I print it out like this:

for i in range(len(l)):
    print "Teams{}\t\t ".format(i+1),
print
for x in itertools.izip_longest(*l, fillvalue="."):
    print "\n"
    t =  "\t\t ".join(str(i) for i in x)
    print t

Which results in:

Teams1        Teams2          Teams3          Teams4          Teams5          Teams6


name9        name4       name10      name7       name5       name


name2        name11      name3       name6       name8       .

Is there any way I can get an output like this:

Team 1      Team 2      Team 3      Team 4      Team 5      Team 6
-------------------------------------------------------------------
name9       name4       name10      name7       name5       name
name2       name11      name3       name6       name8       .

And just align them properly?

Community
  • 1
  • 1
Beginner
  • 2,643
  • 9
  • 33
  • 51

6 Answers6

6

Alternatively, if you don't want to use a third party library:

from itertools import izip_longest

data = [['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]

length = max(len(name) for names in data for name in names)
gutter = 5

format_string = '{{:<{}}}'.format(length + gutter)

print ''.join(format_string.format('Team {}'.format(x)) for x in range(len(data)))
print '-' * len(data) * (length + gutter)
for names in izip_longest(*data, fillvalue='.'):
    print ''.join(format_string.format(name) for name in names)

Produces:

Team 0     Team 1     Team 2     Team 3     Team 4     Team 5
------------------------------------------------------------------
name9      name4      name10     name7      name5      name
name2      name11     name3      name6      name8      .
Ben
  • 6,687
  • 2
  • 33
  • 46
2

This uses the string method ljust() to left-justify each item instead of relying on multiple tabs and custom print endings (placed into an if block in the interpreter so you can see the whole table at once):

>>> if 1:
...     print "".join(  ("Teams" + str(i+1)).ljust(10) for i in xrange(10))
...     print
...     for x in itertools.izip_longest(*l, fillvalue="."):
...             print "".join(str(i).ljust(10) for i in x)
...
Teams1    Teams2    Teams3    Teams4    Teams5    Teams6    Teams7    Teams8    Teams9    Teams10

name9     name4     name10    name7     name5     name
name2     name11    name3     name6     name8     .
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

Use prettytable

from prettytable import PrettyTable

teams = ['team%d'%(x+1) for x in range(len(l)) ]
x = PrettyTable(teams)
for i in itertools.izip_longest(*l, fillvalue="."):
    x.add_row(i)
x.vertical_char = ' '
x.junction_char = '-'

print(x)

---------------------------------------------------
  team1   team2    team3    team4   team5   team6  
---------------------------------------------------
  name9   name4    name10   name7   name5    name  
  name2   name11   name3    name6   name8     .    
---------------------------------------------------

lines = x.get_string().split('\n')
output = '\n'.join(lines[1:-1])
print(output)

team1   team2    team3    team4   team5   team6  
---------------------------------------------------
name9   name4    name10   name7   name5    name  
name2   name11   name3    name6   name8     .  
dermen
  • 5,252
  • 4
  • 23
  • 34
1

It can be done by building everything line by line:

teams = {'Teams 1': ['name9', 'name2'], 
         'Teams 2': ['name4', 'name11'],
        'Teams 3':['name10']}

print teams

line1 = []
line2 = []
line3 = []

for key, value in teams.iteritems():
    line1.append(key)
    line2.append(value[0])
    if len(value) == 2:
        line3.append(value[1])
    else:
        line3.append(".")

def build_row(line, max_width=20):
    linef = ''
    for i in line:
        spaces = max_width - len(i)
        linef += i
        linef += ' '*spaces
    return linef

row1 = build_row(line1)
print row1
print '-'*len(row1)
print build_row(line2)
print build_row(line3)

>>> 
Teams 1             Teams 3             Teams 2             
------------------------------------------------------------
name9               name10              name4               
name2               .                   name11    
kezzos
  • 3,023
  • 3
  • 20
  • 37
1

why not string formatting https://docs.python.org/2/library/string.html#format-specification-mini-language

l = [['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]
cell = "{:<10}"

for i in range(len(l)):
    hdr = "Teams{}".format(i+1)
    print(cell.format(hdr), end="")
print("\n")
print("-"*60)      
for x in zip_longest(*l, fillvalue="."):    
    t =  "".join(cell.format(i) for i in x)
    print( t + "\n")

sorry I was using python 3.4 so my print requires ()

corn3lius
  • 4,857
  • 2
  • 31
  • 36
0

Try tabview: https://pypi.python.org/pypi/tabview/.

It can be used both as a cli tool as a python module:

import tabview as t
a = [["a","b","c"], ["d","e","f"]]
t.view(a)
thule
  • 4,034
  • 21
  • 31