Created
March 26, 2014 17:35
-
-
Save eirenik0/9788876 to your computer and use it in GitHub Desktop.
print table in console
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 printTable( data, header=None ): | |
lens = [0]*len(data[0]) | |
for row in data: | |
for numCol, column in enumerate(row): | |
cLen = len(str(column)) | |
if lens[numCol] < cLen: | |
lens[numCol] = cLen | |
res = "" | |
spacer = lambda lenList: '+' + '+'.join( '-'*(x+2) for x in lenList ) + '+' | |
drawRow = lambda lenList, valueList: '|' + "".join( | |
' %s ' % item + ' ' * (lenList[num] - len(str(item))) + '|' | |
for num, item in enumerate(valueList) ) | |
if header: | |
for numCol, column in enumerate(header): | |
cLen = len(str(column)) | |
if lens[numCol] < cLen: | |
lens[numCol] = cLen | |
res += spacer(lens)+ "\n" | |
res += drawRow( lens, header )+ "\n" | |
res+= spacer(lens) + "\n" | |
for r in data: | |
res += drawRow( lens, r )+ "\n" | |
res+= spacer(lens)+ "\n" | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
header: printTable([[1,2,3],[4,5,6]], ['col 1', 'col 2', 'col 3'])
+-------+-------+-------+
| col 1 | col 2 | col 3 |
+-------+-------+-------+
| 1 | 2 | 3 |
| 4 | 5 | 6 |
+-------+-------+-------+