快速提问,希望你们能帮忙:
这是我的密码:
def nd_mkboard(dims, filler):
n = len(dims)
helpboard = [filler]
helpboard = helpboard * dims[n-1]
for i in reversed(range(n)):
if i != 1:
helpboard = [helpboard] * dims[i-1]
return helpboard
例如:
stuff = nd_mkboard([2, 4, 2], False)
print(stuff)
[[[False, False], [False, False], [False, False], [False, False]],
[[False, False], [False, False], [False, False], [False, False]]]
stuff[0][0][0] = True
print(stuff)
[[[True, False], [True, False], [True, False], [True, False]],
[[True, False], [True, False], [True, False], [True, False]]]
如何避免此链接问题?我想要的是:
[[[True, False], [False, False], [False, False], [False, False]],
[[False, False], [False, False], [False, False], [False, False]]]
见this question。你知道吗
列表是引用。所以复制一个列表就是复制引用,这意味着你最终指向同一个东西。你知道吗
将列表相乘就是生成多个副本,如上所述。你知道吗
为了解决这个问题,可以使用
list[:]
切片表示法来克隆列表,或者构造代码以在每次迭代中创建新的列表。你知道吗就复制而言,你几乎注定要失败,因为这是你想要避免的。可以使用^{} ,但最好只编写一个递归函数。你知道吗
更新:
下面是一个递归构建结构的函数,它还可以处理构造的对象。你知道吗
更新2:
列表而不是参数:
相关问题 更多 >
编程相关推荐