I was trying to find a way to auto-generate a nested list with filler data that does not result in shallow copying problems (i.e., when I change one value, a whole bunch of values change). This is what I figured out using list comprehensions. Hence, it should be quite efficient. Error checking could be built-in but I didn't feel the need.
#builds a nested list from the inner-most list to the outer-most
#listRangeTuples: must be a list or tuple of tuples to fill the
# range values
#degree: number of degrees or levels of nesting
#theList: this is the variable that passes the lower nest at
# each point; it also sets the default value
import copy
def nestedListBuilder(listRangeTuples, degree=3, theList=None):
if degree == 0:
return theList
x = [copy.deepcopy(theList) for i in range \
(listRangeTuples[0][0],
listRangeTuples[0][1])] return nestedListBuilder(listRangeTuples[1:], degree-1, x)
No comments:
Post a Comment
A place in which to share your thoughts...