Created
December 10, 2017 20:26
-
-
Save cmattoon/a3cba1b85650c5fc285ffccae70b98ba to your computer and use it in GitHub Desktop.
Python - Pretty-Print Tabular Data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from typing import List | |
def ptable(data : List[List], sep : str = "\t", sort_by : int = None): | |
""" | |
Pretty-prints a table | |
Args: | |
data (list): A list of lists where data[0] = the first row | |
sep (str): Default "\t" - the separator to use | |
sort_by (int): Default None - the column index to sort by | |
""" | |
if sort_by is not None: | |
data.sort(key=lambda x: x[sort_by]) | |
# The max length of column i | |
cmax = [0 for i in range(len(data[0]))] | |
for row in data: | |
for i, m in enumerate(cmax): | |
cmax[i] = max(m, len(str(row[i]))) | |
for row in data: | |
cells = ["{}".format(row[i]).ljust(cmax[i]) for i in range(len(row))] | |
print(sep.join(cells)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment