Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print list in table format in python

Tags:

python

tabular

I am trying to print several lists (equal length) as columns of an table.

I am reading data from a .txt file, and at the end of the code, I have 5 lists, which I would like to print as columns separated but space.

like image 470
Blaise Delaney Avatar asked Jun 24 '13 15:06

Blaise Delaney


People also ask

How do I print a list of data in Python?

Using the * symbol to print a list in Python. To print the contents of a list in a single line with space, * or splat operator is one way to go. It passes all of the contents of a list to a function. We can print all elements in new lines or separated by space and to do that, we use sep=”\n” or sep=”, ” respectively.


2 Answers

I'll show you a 3-list analog:

>>> l1 = ['a', 'b', 'c']
>>> l2 = ['1', '2', '3']
>>> l3 = ['x', 'y', 'z']
>>> for row in zip(l1, l2, l3):
...     print ' '.join(row)

a 1 x
b 2 y
c 3 z
like image 113
arshajii Avatar answered Sep 21 '22 04:09

arshajii


You can use my package beautifultable . It supports adding data by rows or columns or even mixing both the approaches. You can insert, remove, update any row or column.

Usage

>>> from beautifultable import BeautifulTable
>>> table = BeautifulTable()
>>> table.column_headers = ["name", "rank", "gender"]
>>> table.append_row(["Jacob", 1, "boy"])
>>> table.append_row(["Isabella", 1, "girl"])
>>> table.append_row(["Ethan", 2, "boy"])
>>> table.append_row(["Sophia", 2, "girl"])
>>> table.append_row(["Michael", 3, "boy"])
>>> print(table)
+----------+------+--------+
|   name   | rank | gender |
+----------+------+--------+
|  Jacob   |  1   |  boy   |
+----------+------+--------+
| Isabella |  1   |  girl  |
+----------+------+--------+
|  Ethan   |  2   |  boy   |
+----------+------+--------+
|  Sophia  |  2   |  girl  |
+----------+------+--------+
| Michael  |  3   |  boy   |
+----------+------+--------+

Have fun

like image 37
Priyam Singh Avatar answered Sep 18 '22 04:09

Priyam Singh