Last active
February 23, 2024 06:52
-
-
Save mibmo/dc66092a43888a8620f312be477e2261 to your computer and use it in GitHub Desktop.
Print a Python table (list of lists)
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
def print_table(table, *fields, padding=2): | |
'''Pretty prints a table (iterable of iterables) with given header fields''' | |
data = [fields] + table | |
column_width = max(len(str(column)) for row in data for column in row) + padding | |
[print("".join(str(column).ljust(column_width) for column in row)) for row in data] | |
table = [ | |
("Ada", "Lovelace", 36), | |
("Bjarne", "Stroustrup", 73), | |
("Ken", "Thomson", 81), | |
("Linus", "Torvalds", 54), | |
("Radia", "Perlman", 72), | |
] | |
print_table(table, "First name", "Last name", "Age") | |
''' | |
output: | |
First name Last name Age | |
Ada Lovelace 36 | |
Bjarne Stroustrup 73 | |
Ken Thomson 81 | |
Linus Torvalds 54 | |
Radia Perlman 72 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment