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)?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.