2017-03-06 43 views
1

快速的问题,希望你们能帮助:创建列表利用乘法而不是让每个表镜

这里是我的代码:

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]]] 

回答

2

请参阅this question

列表是参考。所以复制一个列表就是复制引用,这意味着你指向相同的东西。

如上所述,将列表乘以多个副本。

要解决此问题,请使用list[:]切片符号来克隆列表,或者构造代码以在每次迭代中创建新列表。

就复制过程而言,你几乎注定要失败,因为这就是你想避免的。你可以使用copy.deepcopy,但你最好只写一个递归函数。

更新:

下面是递归构建结构,并且可以处理构造的对象和函数。

def make_structure(dim1, *args, fill=None): 
    fill = False if fill is None else fill 
    get_fill = lambda: fill() if callable(fill) else fill 

    result = [] 
    for i in range(dim1): 
     if len(args): 
      result.append(make_structure(*args, fill=fill)) 
     else: 
      result.append(get_fill()) 

    return result 

lines = [2,4,2] 

s = make_structure(2,4,2) 
print(s) 
s[0][0][0] = True 
print(s) 

class TestObj: 
    def __init__(self): 
     self.id = id(self) 

    def __repr__(self): 
     return str(self.id) 

s = make_structure(2,4,2,fill=TestObj) 
print(s) 
s[0][2][1] = TestObj() 
print(s) 

更新2:

列表,而不是ARGS:

def make_structure(dims, fill=None): 
    fill = False if fill is None else fill 
    get_fill = lambda: fill() if callable(fill) else fill 

    result = [] 
    for i in range(dims[0]): 
     if len(dims) > 1: 
      result.append(make_structure(dims[1:], fill=fill)) 
     else: 
      result.append(get_fill()) 

    return result 
+0

太谢谢你了。任何启动递归函数的提示? –

+0

该函数是**递归**。葛丽泰嘉宝是**隐居。** :-)我已经添加了一个更新。 –

+0

这绝对美妙,非常感谢。最后一个问题,无论如何要传递昏暗的列表而不是多个参数?抱歉打扰你。例如,make_structure([2,4,2])而不是make_structure(2,4,2)。 –

相关问题