3

I have a list of data that looks something like this:

[
    (
        1,
        u'python -c \'print("ok")\'',
        u'data',
        u'python'
    ), (
        2,
        u'python -c \'print("this is some data")\'',
        u'data',
        u'python'
    )
]

This data is taken out of a database and displayed as this, and is continuously growing. What I would like to do is display the data like this:

Language  |  Type  |   Payload
-------------------------------
 python   |  data  |  python -c 'print("ok")'
 python   |  data  |  python -c 'print("this is some data")'

I have a function that kinda does the same thing, but it's not exactly as expected:

def print_table(data, cols, width):
    n, r = divmod(len(data), cols)
    pattern = "{{:{}}}".format(width)
    line = "\n".join(pattern * cols for _ in range(n))
    last_line = pattern * r
    print(line.format(*data))
    print(last_line.format(*data[n*cols]))

How can I get the output of my data to look as wanted? From the answers it's possible with pandas but I would also like a way to do it without installing external modules

13aal
  • 1,634
  • 1
  • 21
  • 47

3 Answers3

2

Analyze the data for its max-width and use string formatting - some 'creative' formatting later:

data = [
    (
        1,
        u'python -c \'print("ok")\'',
        u'data',
        u'python'
    ), (
        2,
        u'python -c \'print("this is some data")\'',
        u'data',
        u'python'
    )
]



def print_table(data):
    widths = {0:0, 3:len("Language"),2:len("Type"),1:len("Payload")}
    for k in data:
        for i,d in enumerate(k): 
            widths[i] = max(widths[i],len(str(d))) 
    # print(widths)

    lan, typ, pay = ["Language","Type","Payload"]
    print(f"{lan:<{widths[3]}}  |  {typ:<{widths[2]}}  |  {pay:<{widths[1]}}")
    # adjust by 10 for '  |  ' twice
    print("-" * (widths[1]+widths[2]+widths[3]+10)) 
    for k in data:
        _, pay, typ, lan = k
        print(f"{lan:<{widths[3]}}  |  {typ:<{widths[2]}}  |  {pay:<{widths[1]}}") 

Output:

Language  |  Type  |  Payload                               
------------------------------------------------------------
python    |  data  |  python -c 'print("ok")'               
python    |  data  |  python -c 'print("this is some data")'

Equivalent Python 2.7 code:

# w == widths - would break 79 chars/line else wise
def print_table(data):
    w = {0:0, 3:len("Language"),2:len("Type"),1:len("Payload")}
    for k in data:
        for i,d in enumerate(k): 
            w[i] = max(w[i],len(str(d))) 


    lan, typ, pay = ["Language","Type","Payload"]
    print "{:<{}}  |  {:<{}}  |  {:<{}}".format(lan, w[3], typ, w[2], pay, w[1])   
    print "-" * (w[1]+w[2]+w[3]+10) 
    for k in data:
        _, pay, typ, lan = k
        print "{:<{}}  |  {:<{}}  |  {:<{}}".format(lan, w[3], typ, w[2], pay, w[1]) 
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Is there a way to do this and be compatible with both 2.x and 3+? 2.x doesn't support the `f""` – 13aal Nov 27 '18 at 16:59
  • 1
    @13aal you can convert the `f'strings'` into normal `.format()` syntax - see edit - sorry for not seeing the python 2.7 tag - python2 does not use print() as function though - so its not compatible this way - you might want to import print from future: [how-to-use-from-future-import-print-function](https://stackoverflow.com/questions/32032697/how-to-use-from-future-import-print-function) – Patrick Artner Nov 27 '18 at 17:15
2

Solution that handles any number of columns:

from operator import itemgetter

data = [
    ('ID', 'Payload', 'Type', 'Language'),
    (1, u'python -c \'print("ok")\'', u'data', u'python'),
    (2, u'python -c \'print("this is some data")\'', u'data', u'python')
]


def print_table(data):
    lengths = [
        [len(str(x)) for x in row]
        for row in data
    ]

    max_lengths = [
        max(map(itemgetter(x), lengths))
        for x in range(0, len(data[0]))
    ]

    format_str = ''.join(map(lambda x: '%%-%ss | ' % x, max_lengths))

    print(format_str % data[0])
    print('-' * (sum(max_lengths) + len(max_lengths) * 3 - 1))

    for x in data[1:]:
        print(format_str % x)

print_table(data)

Output:

$ python table.py
ID | Payload                                | Type | Language |
---------------------------------------------------------------
1  | python -c 'print("ok")'                | data | python   |
2  | python -c 'print("this is some data")' | data | python   |
cody
  • 11,045
  • 3
  • 21
  • 36
1

You can use pandas for that:

import pandas as pd
data = pd.DataFrame(a, columns=['id','Payload', 'type', 'Language'])
print(data)

gives you:

   id                                 Payload  type Language
0   1                 python -c 'print("ok")'  data   python
1   2  python -c 'print("this is some data")'  data   python
Pedro Borges
  • 1,240
  • 10
  • 20