使用乘法创建列表,但没有每个列表镜像 [英] Create a list utilizing multiplication but not have each list mirror

查看:70
本文介绍了使用乘法创建列表,但没有每个列表镜像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,希望你们能提供帮助:

Quick question, hope you guys can help:

这是我的代码:

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

如何避免这种链接问题?我想要的是:

How do I avoid this linkage problem? All I want is:

[[[True, False], [False, False], [False, False], [False, False]], 
[[False, False], [False, False], [False, False], [False, False]]]

推荐答案

请参见这个问题.

列表是参考.因此,复制列表即复制引用,这意味着您最终指向同一件事.

Lists are references. So copying a list is copying references, which means you wind up pointing to the same thing.

与上面一样,将列表相乘会产生多份副本.

Multiplying a list is making multiple copies, as above.

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

To get around this problem, use the list[:] slice notation to clone the list, or structure your code to create new lists each iteration.

就复制而言,您几乎注定要失败,因为这是您要避免的事情.您可以使用 copy.deepcopy ,但是编写递归函数可能会更好.

You're pretty much doomed as far as making copies goes, since that's what you want to avoid. You could use copy.deepcopy, but you might be better off just writing a recursive function.

更新:

这是一个递归构建结构的函数,并且还可以处理构造的对象.

Here's a function that recursively builds the structure, and can handle constructed objects as well.

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

这篇关于使用乘法创建列表,但没有每个列表镜像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆