Better way to initialize multidimensional array with mutable object
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 is开发者_开发问答instance(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)?
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.
精彩评论