Saturday, March 9, 2013

Python Nested List

In a previous post, I outlined a python function for creating nested lists. In retrospect, it was a naive, if functional, first attempt. As the size of the various dimensions increases, the function would become quite slow largely as a result of the deepcopy calls and recursion. A more efficient method would use the following syntax:

nestedList = [[[baseValue for x in range(axisLength)] 
                for y in range(axisLength)] for z in ...]

Now, a naive attempt to turn this into a function might do something like the following:

def nestedList(axisLength, degree, base):
  for x in range(degree):
    base = [base for y in range(axisLength)]
  return base

But this will actually just create shallow copies. The problem is that base is not recreated at each iteration. However, this is fixable with generators. For example:

def baseGen(base, axisLength):   
  while True:
      yield [ for x in range(axisLength)]
    except AttributeError:
      yield [base for x in range(axisLength)]

def nestedList(base, axisLength, degree):
  for d in range(degree):
    base = baseGen(base, axisLength)
  return base

Then, you would just call nList = nestedList(None, 5, 3) and then ls = for a 5x5x5 cube with None as the base value. An added advantage of using generators is that you can just keep calling every time you want a new cube.

No comments:

Post a Comment

A place in which to share your thoughts...