Python 3.x 简单单位矩阵函数
预期产出:Python 3.x 简单单位矩阵函数,python-3.x,list,for-loop,matrix,computer-science,Python 3.x,List,For Loop,Matrix,Computer Science,预期产出: indenitiy_matrix(3) [[1, 0, 0], [0, 1, 0], [0, 0, 1]] 带错误的实际输出: indenitiy_matrix(3) [[1, 1, 1], [1, 1, 1], [1, 1, 1]] list_template*n不会创建n个副本,而是所有这些n个副本只引用一个副本。比如,你看这个 a = [[0,0,0]]*2 # Now, lets change first element of the first sublist in
indenitiy_matrix(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
带错误的实际输出:
indenitiy_matrix(3)
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
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]]
[[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]]
修正你的代码
输出:
[[1, 0, 0], [1, 0, 0]]
[[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提供的链接:
最后,numpy库是您创建标识矩阵和其他N维数组的朋友。您的问题是由此问题中解释的问题引起的:非常感谢您对我的问题的简单而完整的回答。我是一名学习python的工科学生,以前从未尝试过这个网站。知道某个完全陌生的人出于善意帮助了我,我非常高兴。我非常感激。再次感谢。我复制粘贴了我为上述答案所写的评论,因为我对您的回复也有同样的感受。::非常感谢你对我的问题的简单而完整的回答。我是一名学习python的工科学生,以前从未尝试过这个网站。知道某个完全陌生的人出于善意帮助了我,我非常高兴。我非常感激。再次感谢。