Python 列表中的项目替换不正常
Python 列表中的项目替换不正常,python,python-3.x,Python,Python 3.x,cria_mundo创建一个由0组成的矩阵,其中linhas是行数,colunas是矩阵中的列数。每行由colunas元素组成,因此基本上如果linhas=2和colunas=3它将返回一个类似[[0,0,0],[0,0,0]]]的列表 现在,我想使用itera_mundo,其中mundo也是列表中的一个矩阵。此函数采用cria_mundo并向mundo矩阵添加两列和两行,每边一行,基本上将mundo矩阵封装在一个0的框中。 这就是它应该如何工作,但它没有,因为如果mundo是[[1,0],[0
cria_mundo
创建一个由0组成的矩阵,其中linhas
是行数,colunas
是矩阵中的列数。每行由colunas
元素组成,因此基本上如果linhas=2
和colunas=3
它将返回一个类似[[0,0,0],[0,0,0]]]
的列表
现在,我想使用itera_mundo
,其中mundo
也是列表中的一个矩阵。此函数采用cria_mundo
并向mundo
矩阵添加两列和两行,每边一行,基本上将mundo
矩阵封装在一个0的框中。
这就是它应该如何工作,但它没有,因为如果mundo
是[[1,0],[0,1]]
它会输出[[0,0,0,0,0,0],[0,1,0,0],[0,0,0,1,0],[0,0,1,0],[0,1,0],[0,1,0],[0,1,0],[0,1,0]
如果没有导入、中断或继续,我如何修复此问题?以下是我的解决方案
def itera_mundo(mundo):
colunas = len(mundo[0])
linhas = len(mundo)
ncolunas = colunas + 2
nlinhas = linhas + 2
novo_mundo=cria_mundo(nlinhas,ncolunas)
for linha in range(linhas):
for coluna in range(colunas):
if mundo[linha][coluna] == 1:
novo_mundo[linha+1][coluna+1] = 1
return novo_mundo
def cria_mundo(linhas, colunas):
mini_matriz = []
matriz = []
for x in range(colunas):
mini_matriz.append(0)
for z in range(linhas):
matriz.append(mini_matriz)
return matriz
print(itera_mundo([[1,0],[0,0]]))
输出
def itera_mundo(mundo):
colunas = len(mundo[0])+2
linhas = len(mundo)+2
novo_mundo=cria_mundo(linhas,colunas)
for row in range(1,len(novo_mundo)-1):
novo_mundo[row][1:-1] = mundo[row-1]
return novo_mundo
def cria_mundo(linhas, colunas):
return [[0 for c in range(colunas)] for l in range(linhas)]
print(itera_mundo([[1,0],[0,1]]))
输出:
def itera_mundo(mundo):
colunas = len(mundo[0])
linhas = len(mundo)
ncolunas = colunas + 2
nlinhas = linhas + 2
novo_mundo=cria_mundo(nlinhas,ncolunas)
for linha in range(linhas):
for coluna in range(colunas):
if mundo[linha][coluna] == 1:
novo_mundo[linha+1][coluna+1] = 1
return novo_mundo
def cria_mundo(linhas, colunas):
mini_matriz = []
matriz = []
for x in range(colunas):
mini_matriz.append(0)
for z in range(linhas):
matriz.append(mini_matriz[:])
return matriz
print(itera_mundo([[1,0],[0,0]]))
问题出现在“范围内的z(linhas):matriz.append(mini_matriz)”>>中,这里我们将在“matriz”中插入与多个条目相同的“mini_matriz”。在出现在matriz之前,应复制/克隆“mini_matriz”。
def itera_mundo(mundo):
colunas = len(mundo[0])
linhas = len(mundo)
ncolunas = colunas + 2
nlinhas = linhas + 2
novo_mundo=cria_mundo(nlinhas,ncolunas)
for linha in range(linhas):
for coluna in range(colunas):
if mundo[linha][coluna] == 1:
novo_mundo[linha+1][coluna+1] = 1
return novo_mundo
def cria_mundo(linhas, colunas):
mini_matriz = []
matriz = []
for x in range(colunas):
mini_matriz.append(0)
for z in range(linhas):
matriz.append(mini_matriz[:])
return matriz
print(itera_mundo([[1,0],[0,0]]))
>python mundo.py
[[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]