使用可变对象初始化多维数组的更好方法
我想创建一个多维数组并用 a 的副本初始化它 可变对象。这就是我到目前为止所拥有的:
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 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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样:
这将创建一个由
C
的唯一实例组成的2x3x4
数组。解决方案仍然是递归的,但我认为递归非常适合这个问题。
How about:
This creates a
2x3x4
array of unique instances ofC
.The solution is still recursive, but I think recursion is a pretty good fit for this problem.