colalove
colalove

Reputation: 31

How to print a list of lists in a grid format?

If I have a list of lists like ([1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15]) How can I print it on the screen in a grid format? Just like:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15

My code is like

def print_table(listx):
    """returns a grid of a list of lists of numbers

    list of list -> grid"""
    for lists in listx:
        for i in lists:
            print(i,end='\t')

But I don't know how to make each list in a single row like example above.

Upvotes: 3

Views: 13235

Answers (3)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23253

My solution creates string with space-separated numbers in rows and \n-separated rows. It's using str.center method and generator-expressions.

str.center(width[, fillchar])

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

def as_string(seq_of_rows):
    return '\n'.join(''.join(str(i).center(5) for i in row) for row in seq_of_rows)
l = ([1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15])
print as_string(l)

Output:

  1    2    3    4    5  
  2    4    6    8    10 
  3    6    9    12   15

Let's break it up:

str(i).center(5) for i in row

It iterates over row, converts values to strings and calls center method. Result is space-padded values.

''.join(sequence_above)

It creates single string from values. So now, string contains whole row.

'\n'.join(processed_row row in seq_of_rows)

It takes processed rows (strings)from previous step and joins them using newline character, so result is row1\nron2\nrow3.

Upvotes: 0

fferri
fferri

Reputation: 18950

If the width of your elements varies more than tab width, you can use fixed width columns (filled by spaces):

>>> for x in listx:
...     for y in x:
...         print('{0:<10}'.format(y), end='')
...     print()
...
1         2         3         4         5
2         4         6         8         10
3         6         9         12        15

Upvotes: 0

luislhl
luislhl

Reputation: 1506

Maybe just adding an empty print on the main for:

def print_table(listx):
    """returns a grid of a list of lists of numbers

    list of list -> grid"""
    for lists in listx:
        for i in lists:
            print(i,end='\t')
        print()

Upvotes: 2

Related Questions