【问题标题】:Create a list utilizing multiplication but not have each list mirror利用乘法创建一个列表,但没有每个列表镜像
【发布时间】:2017-07-26 15:56:49
【问题描述】:

快速提问,希望大家帮忙:

这是我的代码:

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

【问题讨论】:

    标签: python arrays list multidimensional-array mirroring


    【解决方案1】:

    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:

    列表而不是参数:

    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
    

    【讨论】:

    • 非常感谢。启动递归函数的任何提示?
    • 函数是递归的。 Greta Garbo 隐居。 :-) 我添加了更新。
    • 这太棒了,非常感谢。最后一个问题,有没有将一个暗淡作为一个列表而不是多个参数传递?抱歉打扰你。例如,make_structure([2,4,2]) 代替 make_structure(2,4,2)。
    • 好的,修改一下就好了。不是 dim1 而是 dims[0] 和 len(dims)-1 而不是 len(args)。
    • 你太棒了。你不知道你对我的帮助有多大!祝你有美好的一天。
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2020-10-22
    • 2022-01-07
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多