奇怪的清单分配

时间:2014-10-26 11:27:44

标签: list python-3.x

我试图创建一个程序,将列表(lista)的值分配给另一个列表(输出),但程序也在更改第一个列表的值。

def MAXJ(lista):
static = lista
output = lista
for i in range(len(lista)):
    for j in range(len(lista[i])):
        if(i != 0):
            output[i][j] = output[i][j] + lista[i-1][j]
            if(j != 0):
                output[i][j] = output[i][j] + lista[i-1][j-1]
            if(j != len(lista[i])):
                output[i][j] = output[i][j] + lista[i-1][j+1]
        if(i != len(lista)):
            output[i][j] = output[i][j] + lista[i+1][j]
            if(j != 0):
                output[i][j] = output[i][j] + lista[i+1][j-1]
            if(j != len(lista[i])):
                output[i][j] = output[i][j] + lista[i+1][j+1]
        if(j != 0):
            output[i][j] = output[i][j] + lista[i][j-1]
        if(j != len(lista[i])):
            output[i][j] = output[i][j] + lista[i][j+1]
        print("List:", lista, "\n","OutPut:", output)
MAXJ([[1, 2, 3, 2],[0, 0, 1, 2]])

这是控制台

List: [[3, 2, 3, 2], [0, 0, 1, 2]] 
OutPut: [[3, 2, 3, 2], [0, 0, 1, 2]]
List: [[3, 9, 3, 2], [0, 0, 1, 2]] 
 OutPut: [[3, 9, 3, 2], [0, 0, 1, 2]]
List: [[3, 9, 17, 2], [0, 0, 1, 2]] 
 OutPut: [[3, 9, 17, 2], [0, 0, 1, 2]]
Traceback (most recent call last):
  File "C:\Python34\Programs\Logia\Logia13\Etap3\Zadanie4.py", line 23, in <module>
MAXJ([[1, 2, 3, 2],[0, 0, 1, 2]])
  File "C:\Python34\Programs\Logia\Logia13\Etap3\Zadanie4.py", line 17, in MAXJ
    output[i][j] = output[i][j] + lista[i+1][j+1]
IndexError: list index out of range

我不知道为什么lista和输出的值是相同的

1 个答案:

答案 0 :(得分:0)

这里有两点需要注意:

  • 您应该检查i != len(lista) - 1j != len(lista[i]) - 1,因为您可以访问的最后一个列表索引是len(list) - 1(列出从0开始的索引)。 (或者,您可以使用not i < len(lista)not j < len(lista[i]))。
  • 通过分配output = listaoutputlista实际引用相同的对象。这意味着更改output也会更改lista。您要做的是使用deepcopy模块的copy

总而言之:

import copy

def MAXJ(lista):
    static = lista
    output = copy.deepcopy(lista)
    for i in range(len(lista)):
        for j in range(len(lista[i])):
            if(i != 0):
                output[i][j] = output[i][j] + lista[i-1][j]
                if(j != 0):
                    output[i][j] = output[i][j] + lista[i-1][j-1]
                if(j != len(lista[i]) - 1):
                    output[i][j] = output[i][j] + lista[i-1][j+1]
            if(i != len(lista) - 1):
                output[i][j] = output[i][j] + lista[i+1][j]
                if(j != 0):
                    output[i][j] = output[i][j] + lista[i+1][j-1]
                if(j != len(lista[i]) - 1):
                    output[i][j] = output[i][j] + lista[i+1][j+1]
            if(j != 0):
                output[i][j] = output[i][j] + lista[i][j-1]
            if(j != len(lista[i]) - 1):
                output[i][j] = output[i][j] + lista[i][j+1]
            print("List:", lista, "\n","OutPut:", output, sep = '')
MAXJ([[1, 2, 3, 2],[0, 0, 1, 2]])