1

I want to create a multidimensional array and initialize it with copies of a mutable object. This is what I have so far:

import copy

def create_array(dimensions):
    dimensions = copy.deepcopy(dimensions)
    dimensions.reverse()
    a = [0] * dimensions[0]
    del dimensions[0]
    for d in dimensions:
        a = [copy.deepcopy(a) for _ in range(d)]
    return a

def create_array_mutable(dimensions, obj):
    a = create_array(dimensions)
    def set(x):
        if isinstance(x[0], list):
            for e in x:
                set(e)
        else:
            for i in range(len(x)):
                x[i] = copy.deepcopy(obj)
    set(a)
    return a

I wonder if there is a better way to do it (without the copies and the recursion)?

tauran
  • 7,986
  • 6
  • 41
  • 48
  • 4
    if you can use numpy then the first answer here seems to be close to what you are looking for - http://stackoverflow.com/questions/4877624/numpy-array-of-objects (although that is calling the constructor rather than copy...) – andrew cooke Aug 12 '11 at 13:04

1 Answers1

2

How about:

import copy

def create_array_mutable(dims, obj):
  if len(dims) == 0:
    return copy.deepcopy(obj)
  else:
    return [create_array_mutable(dims[1:], obj) for i in xrange(dims[0])]

class C(object): pass

print create_array_mutable((2,3,4), C())

This creates a 2x3x4 array of unique instances of C.

The solution is still recursive, but I think recursion is a pretty good fit for this problem.

NPE
  • 486,780
  • 108
  • 951
  • 1,012