Skip to content

Instantly share code, notes, and snippets.

@munro
Forked from djmunro/foo.py
Last active December 10, 2015 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munro/7b29f8baf903e04b44cf to your computer and use it in GitHub Desktop.
Save munro/7b29f8baf903e04b44cf to your computer and use it in GitHub Desktop.
print_grid(
columns=('Function', 'Occurences', 'Sender'),
values=[(x['function'], 1337, x['sender']) for x in messages if 'function' in x]
)
def print_grid(columns, values, spacing=1, separator='|'):
header_str = ''
format_str = ''
for index in range(len(columns)):
longest = max([len(str(row[index])) for row in [columns] + values])
header_str += '{:' + str(longest) + '}'
format_str += '{:' + str(longest) + '}'
if index != len(columns) - 1:
header_str += ' ' * spacing
format_str += ' ' * spacing
if separator:
header_str += ' ' * (len(separator) + spacing)
format_str += separator + ' ' * spacing
print header_str.format(*columns)
for row in values:
print format_str.format(*row)
print_grid(
columns=('Function', 'Occurences', 'Sender'),
values=[
('hey', 'world', 'foobar'),
('this is', 'a test', 'my man!'),
('roar', 'grr', 'zzzz'),
]
)
"""
Function Occurences Sender
hey | world | foobar
this is | a test | my man!
roar | grr | zzzz
"""
def print_grid(columns, values):
# pop columns on top of values, since we want to print them as well
values = [columns] + values
# calculate the format string for printing a row
row_format = ''
for index in range(len(columns)):
longest = max([len(str(row[index])) for row in values])
row_format += '{:' + str(longest) + '} '
# print the row!
for row in values:
print row_format.format(*row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment