gpt4 book ai didi

python - 当我尝试在数据矩阵上添加一层时出了问题(python)

转载 作者:行者123 更新时间:2023-11-30 22:25:03 25 4
gpt4 key购买 nike

所以假设我这里有一个矩阵,一个包含 0 元组的元组:

matrix = ((0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0),)

我想在它的外面加一层int(1),这样它看起来像:

[[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1],]

首先,我想将此矩阵转换为列表,因为元组不可更改:

matrix_new = list(map(lambda x: list(x), matrix))

然后我想在它的开头和结尾添加一行。

addrow = list(map(lambda x: 1, range(len(matrix[0]))))
matrix_new.insert(0, addrow)
matrix_new.append(addrow)

现在,如果我:

for i in matrix_new:
print(i)
>>>
[1, 1, 1, 1, 1, 1]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1]

到目前为止看起来不错。现在我想在matrix_new的每一行的开头和结尾添加一个int(1):

for i in matrix_new:
i.insert(0, 1)
i.append(1)
print(i)

不知何故现在看起来像:

>>>    
[1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

最后一行似乎有 2 个额外的 int(1)??????现在,如果我:

for i in matrix_new:
print(i)

我得到了:

>>>
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 0, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

现在我得到了第一行还有 2 个额外的 int(1)。

可能出了什么问题?我不明白为什么会发生这种情况。

最佳答案

问题是您附加到矩阵的第一行和最后一行实际上是同一列表的别名,因此您要附加两次。您需要修改您的代码,也许像这样:

addrow1 = list(map(lambda x: 1, range(len(matrix[0]))))
addrow2 = list(map(lambda x: 1, range(len(matrix[0]))))
matrix_new.insert(0, addrow1)
matrix_new.append(addrow2)

关于python - 当我尝试在数据矩阵上添加一层时出了问题(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47645719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com