Advertisement
mengyuxin

meng.printTable.py

Dec 31st, 2017
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. #! python3
  2. # printTable.py
  3.  
  4. tableData = [['apples', 'oranges', 'cherries', 'banana'],
  5.              ['Alice', 'Bob', 'Carol', 'David'],
  6.              ['dogs', 'cats', 'moose', 'goose'],
  7.              ['Dalian', 'Beijing', 'Nanjing', 'Tokyo'],
  8.              ['Red', 'Yellow', 'White', 'Black'],
  9.              ['Accenture', 'IBM', 'HP', 'SAP']]
  10.  
  11. def colWidth(tableData):
  12.     colWidths = [0]*len(tableData)
  13.     for col in range(len(tableData)):
  14.         for item in tableData[col]:
  15.             if len(item) > colWidths[col]:
  16.                 colWidths[col] = len(item)
  17.     return colWidths
  18.  
  19. def printTable(tableData):
  20.     length = colWidth(tableData)
  21.  
  22.     print('row = ' + str(len(tableData[0])), end = ',')
  23.     print('col = ' + str(len(tableData)))
  24.    
  25.     for row in range(len(tableData[0])):
  26.         for col in range(len(tableData)):
  27.             print(tableData[col][row].ljust(length[col]), end = ' ')
  28.         print('')
  29.  
  30. printTable(tableData)
  31.  
  32. """ result:
  33. row = 4,col = 6
  34. apples   Alice dogs  Dalian  Red    Accenture
  35. oranges  Bob   cats  Beijing Yellow IBM      
  36. cherries Carol moose Nanjing White  HP        
  37. banana   David goose Tokyo   Black  SAP
  38. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement