使用乘法创建一个列表,但不要让每个列表都使用mi

2024-10-02 02:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

快速提问,希望你们能帮忙:

这是我的密码:

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

Tags: infalsetrue密码forlendefprint
1条回答
网友
1楼 · 发布于 2024-10-02 02:34:19

this question。你知道吗

列表是引用。所以复制一个列表就是复制引用,这意味着你最终指向同一个东西。你知道吗

将列表相乘就是生成多个副本,如上所述。你知道吗

为了解决这个问题,可以使用list[:]切片表示法来克隆列表,或者构造代码以在每次迭代中创建新的列表。你知道吗

就复制而言,你几乎注定要失败,因为这是你想要避免的。可以使用^{},但最好只编写一个递归函数。你知道吗

更新:

下面是一个递归构建结构的函数,它还可以处理构造的对象。你知道吗

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

相关问题 更多 >

    热门问题