1

Using Python 2.4, how do I print a list in a nice tabular format?

My list is in the below format.

mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), AGGREGATE_VALUE)]

I have tried pprint, but it does not print the result in a tabular format.

EDIT : I would like to see the output in the below format:


VAL1        VAL2     VAL3    VAL4    VAL5    VAL6        AGGREGATE_VALUE


This table, should account for variable item lengths and still print with proper indentation.

GPX
  • 3,506
  • 10
  • 52
  • 69

5 Answers5

8
mylist = [ ( ('12', '47', '4', '574862', '58', '7856'), 'AGGREGATE_VALUE1'),
           ( ('2', '75', '757', '8233', '838', '47775272785'), 'AGGREG2'),
           ( ('4144', '78', '78965', '778', '78578', '2'), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5,6),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))
    longg[6] = max(longg[6],len(str(x)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,7))
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

result

  12  47      4  574862     58         7856  AGGREGATE_VALUE1
   2  75    757    8233    838  47775272785           AGGREG2
4144  78  78965     778  78578            2  AGGREGATE_VALUE3

Don't know if this fills your need

EDIT 1

Using string formatting with modulo operator (%) to print in a constant length, '%6s' right-justifies in a constant length of 6, and '%-6s' left-justifies in a constant length of 6.

You'll find precisions here

But there is no sense to specify a constant length to print something at the end of a string, because it's somewhat naturally-left-justified in this case. Then :

longg = dict.fromkeys((0,1,2,3,4,5,),0)

for tu,x in mylist:
    for i,el in enumerate(tu):
        longg[i] = max(longg[i],len(str(el)))

fofo = '  '.join('%'+str(longg[i])+'s' for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 2

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5),0)

for tu,_ in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))

fofo = '  '.join('%%%ss' % longg[i] for i in xrange(0,6)) + '  %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 3

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
           ( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
           ( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

header = ('Price1','Price2','reference','XYD','code','resp','AGGREG values')

longg = dict(zip((0,1,2,3,4,5,6),(len(str(x)) for x in header)))

for tu,x in mylist:
    longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))
    longg[6] = max(longg[6],len(str(x)))
fofo = ' | '.join('%%-%ss' % longg[i] for i in xrange(0,7))

print '\n'.join((fofo % header,
                 '-|-'.join( longg[i]*'-' for i in xrange(7)),
                 '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)))

result

Price1 | Price2 | reference | XYD    | code  | resp        | AGGREG values   
-------|--------|-----------|--------|-------|-------------|-----------------
12     | 47     | 4         | 574862 | 58    | 7856        | AGGREGATE_VALUE1
2      | 75     | 757       | 8233   | 838   | 47775272785 | AGGREG2         
4144   | 78     | 78965     | 778    | 78578 | 2           | AGGREGATE_VALUE3

Note that this kind of formatting would be much easier with the string's method format() introduced in Python 2.6

eyquem
  • 26,771
  • 7
  • 38
  • 46
  • This is exactly what I was looking for! But how do I left-align all the text? – GPX Jun 02 '11 at 07:51
  • I just tried Edit 1 and it prints out the same right-aligned output! Also, how do I print a header row? – GPX Jun 02 '11 at 09:25
  • Edit 2 gives the same result :-( However, both Edit 1 & 2 gave a left-aligned last column. – GPX Jun 02 '11 at 09:51
  • I didn't understand your question: I thought that speaking of 'all the text', you were speaking of the texts 'AGGREGATE_VALUE1' etc. I still don't understand what you mean by 'left-align all the text'. Do you mean that you want to justify each value of a column at the left of the column ? If so, you must replace '%%%ss' with '%%-%ss' . By the way, Edit 2 wasn't to answer to your comment, it is an improvement – eyquem Jun 02 '11 at 09:54
  • Ah yes! `%%-%ss` did the trick. Yes, I did mean justifying each column value to the left. – GPX Jun 02 '11 at 10:05
  • To print a header row, put its values as first element in mylist, with same format as the other elements. For exemple : **mylist.insert(0,(('Price1','Price2','reference','XYD','code','resp'),'AGGREG values'))** – eyquem Jun 02 '11 at 10:06
  • Yup, figured that out. After I'm done with printing it, I remove it using `del mylist[0]`. – GPX Jun 02 '11 at 10:36
  • Many diverse solutions can be proposed according the data before the treatment. In Edit 3, I give an exemple of what can be done without including the header in the list. This exemple may not be useful for your particular data, but it gives ideas, I think. – eyquem Jun 02 '11 at 10:44
5

Try the texttable module.

Docs: http://foutaise.org/code/texttable/

PyPi: https://pypi.python.org/pypi?name=texttable&:action=display

philfreo
  • 41,941
  • 26
  • 128
  • 141
1

Maybe something like this:

def tabprint(inp):
    for list_el in mylist:
        st = ''
        for word in list_el[0]:
            st += word + '\t' 
        st += str(list_el[1])

    print st
gennad
  • 5,335
  • 12
  • 44
  • 47
0

From your sample output it looks like by "tabular" you might mean tabbed.

If that's correct, this seems work:

mylist=[(('VAL1', 'VAL2', 'VAL3', 'VAL4', 'VAL5', 'VAL6'), 'AGGREGATE_VALUE')]

def flatten(arg):
    if not hasattr(arg, '__iter__'):
        yield arg
    else:
        for i in arg:
            for j in flatten(i):
                yield j

print '\t'.join(flatten(mylist))

Which outputs:

VAL1    VAL2    VAL3    VAL4    VAL5    VAL6    AGGREGATE_VALUE

martineau
  • 119,623
  • 25
  • 170
  • 301
0

For arbitrary item count and arbitrary line count you can use:

print "\n".join (map (lambda (x, y): "%s\t%s" % ("\t".join (x), y), mylist) )

For example for input

mylist = [ ( ('VAL11', 'VAL12', 'VAL13', 'VAL14', 'VAL15', 'VAL16'), 'AGGREGATE_VALUE1'),
     ( ('VAL21', 'VAL22', 'VAL23', 'VAL24', 'VAL25', 'VAL26'), 'AGGREGATE_VALUE2'),
     ( ('VAL31', 'VAL32', 'VAL33', 'VAL34', 'VAL35', 'VAL36'), 'AGGREGATE_VALUE3'),]

it yields:

VAL11   VAL12   VAL13   VAL14   VAL15   VAL16   AGGREGATE_VALUE1
VAL21   VAL22   VAL23   VAL24   VAL25   VAL26   AGGREGATE_VALUE2
VAL31   VAL32   VAL33   VAL34   VAL35   VAL36   AGGREGATE_VALUE3
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87