Fancy Table Printing With Python
Ever want to print out a nice table, maybe have it spaced out nicely? Have you run into a situation where the length of something you want to print differs by more than a tab-length? Stuck in a for loop, with no hope in sight of getting those columns printed nicely? Fear no more!
fancyTable() will accept a multi-dimensional array, and make sure each item in each column is spaced to be as long as the longest element in that column.
For example, should you build up an array of arrays like this:
a = [['Text', '1', 'a'], ['Longer Text', '123', 'abc'], ['Even longer text!', '123456789', 'abcdefghi']]
You'd get this:
Text 1 a Longer Text 123 abc Even longer text! 123456789 abcdefghi
Amazing, isn't it!
def fancyTable(arrays):
def areAllEqual(lst):
return not lst or [lst[0]] * len(lst) == lst
if not areAllEqual(map(len, arrays)):
exit('Cannot print a table with unequal array lengths.')
#lengths = [map(len, a) for a in myar]
#sizes = map(lambda * x:x, *lengths)
#maxSize = [max(a) for a in sizes]
verticalMaxLengths = [max(value) for value in map(lambda * x:x, *[map(len, a) for a in arrays])]
spacedLines = []
for array in arrays:
spacedLine = ''
for i, field in enumerate(array):
diff = verticalMaxLengths[i] - len(field)
spacedLine += field + ' ' * diff + '\t'
spacedLines.append(spacedLine)
return '\n'.join(spacedLines)Let me know what you think! I'm sure there's a better way of doing it.