【问题标题】:Simple Identity matrix function简单单位矩阵函数
【发布时间】:2021-03-01 03:48:38
【问题描述】:

预期输出:

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)

【问题讨论】:

标签: python-3.x list for-loop matrix computer-science


【解决方案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给出的链接:List of lists changes reflected across sublists unexpectedly

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

【讨论】:

  • 我复制粘贴,我为上面的答案写的评论,因为我对你的回复有同样的感觉。 ::: 非常感谢您对我的问题的简单而完整的回答。我是一名学习 python 的工科学生,我以前从未尝试过这个网站。得知某个完全陌生的人出于纯粹的善意帮助了我,我感到非常高兴。我非常非常感激。再次感谢。
【解决方案2】:

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

【讨论】:

  • 非常感谢您对我的问题的简单而完整的回答。我是一名学习 python 的工科学生,我以前从未尝试过这个网站。得知某个完全陌生的人出于纯粹的善意帮助了我,我感到非常高兴。我非常非常感激。再次感谢。
猜你喜欢
  • 2017-03-21
  • 2023-01-16
  • 1970-01-01
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多