简单单位矩阵函数

Simple Identity matrix function

预期输出:

indenitiy_matrix(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

实际输出错误:

indenitiy_matrix(3)
[[1, 1, 1], [1, 1, 1], [1, 1, 1]] 
def identity_matrix(n):
    list_template = [[]]
    list_n = list_template*n

    for sub_l in list_n:
        sub_l.append(0)


    for val in range(n):
        # I have the feeling that the problem lies somewhere around here.
        list_n[val][val]=1


    return(list_n)

list_template*n 不会创建 n 个副本,而是所有 n 个副本仅引用一个副本。例如看这个

a = [[0,0,0]]*2
# Now, lets change first element of the first sublist in `a`. 
a[0][0] = 1
print (a)
# but since both the 2 sublists refer to same, both of them will be changed. 

输出:

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

修复您的代码

def identity_matrix(n):
    list_n = [[0]*n for i in range(n)]
    for val in range(n):        
        list_n[val][val]=1
    
    return list_n

print (identity_matrix(5))

输出:

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

不对,问题出在这里:

list_template = [[]]
list_n = list_template*n

在此之后,尝试做:

list_n[0].append(1)  # let's change the first element

结果:

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

可能不是你所期望的。

简而言之,问题是在构造之后,您的列表包含对同一列表的多个引用。详细解释在@saint-jaeger给出的link:List of lists changes reflected across sublists unexpectedly

最后,numpy 库是您创建单位矩阵和其他 N 维数组的好帮手。