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.
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.
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
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.
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With