Monday, March 7, 2011

Printing a Grid with Python

I'm learning python and I wanted to print a grid (table) of data on the command line from a list

and here is what I ended up with ...


def printGrid(list):
  if list:
    # the character we use to demarc columns
    splitchar = '|'
    # how much padding 
    # (spaces to add to the data in each cell)
    pad = 1 
    # 2d dictionary with each row of data
    myArray = {}
    # the array that keeps count how wide the columns should be
    myColCount = {}
    # how many rows
    rownum = 0
    # how many columns
    colnum = 0
    # how wide the column
    colwidth = 0 


    # find out how many rows we have
    rownum = len(list)
    
    # find out how many columns we have 
    for cols in list[0].split(splitchar):
      # we also initialize the values of 
      # myColCount for each column and 
      # we set it to 0
      myColCount[colnum] = 0
      # increase the colnum value by 1
      colnum += 1 
    
    # for each row ...
    for r in range(rownum):
      # we populate myArray dictionary
      # with a list created by splitting
      # on a defined character (default is |)
      myArray[r] = list[r].split('|')
    
    #loop through columns
    for c in range(colnum):
      #then loop through rows
      for r in range(rownum):
        length = len(myArray[r][c])

        #if the length of the string is bigger or equal 
        # than what is in the myColCount dictionary ...
        if length >= myColCount[c]:
          # we set the new value to length + padding
          # and that is how we populate the myColCount dictionary
          # with column width values
          myColCount[c] = (length + pad)
          colwidth = myColCount[c]

    # for each row of data ...
    for r in range(rownum):
      # we reset str and border on each iteration of this outer loop
      str = ''
      border = ''
      # for each column ...
      for c in range(colnum):
        #all our column widths are stored in the myColCount dictionary
        colwidth = myColCount[c]
        # we set the border by multiplying dashes by the column width
        border += '+' + "%-*s" % (colwidth,'-'*(colwidth))
        # we set the string with a pipe character and set it 
        # to the width specified by colwidth and we use the - to left align
        str += "|" + "%-*s" % (colwidth, myArray[r][c])

      # we add an ending mark and newline
      border += "+\n"
      # we add an ending mark and newline
      str += "|\n"
      print border
      print str
    # we print the bottom border    
    print border

No comments: