列表/矩阵未保存正确的值
我收到的作业有一个奇怪的问题。我们应该实现一个矩阵类。嗯,这并不难,但 Python 就是不会按照我的指示去做。但我确信有一个解释。
问题是,在下面的代码中,我尝试将值(在列表中提供)保存到矩阵中。
class simplematrix:
matrix = [[]]
def __init__(self, * args):
lm = args[0]
ln = args[1]
values = args[2]
self.matrix = [[0]*ln]*lm
for m in range(lm):
for n in range(ln):
self.matrix[m][n] = values[(m*ln)+n]
vals = [0,1,2,3,4,5]
a = simplematrix(2,3,vals)
当我尝试打印矩阵时,我期望得到 [[0,1,2],[3,4,5]],如果我在一张纸上手动运行它,我就会得到它。如果我从 Python 打印矩阵,我会得到 [[3,4,5],[3,4,5]] 。 谁能告诉我为什么Python会这样,或者我是否在某个地方犯了一些愚蠢的错误? :)
I have a weird problem with an assignment I got. We are supposed to implement a matrix class. Well, it's not that hard, but Python just won't do as I tell it to. But I'm sure there is an explanation.
The problem is that, in the following code, I try to save values (provided in a list) into a matrix.
class simplematrix:
matrix = [[]]
def __init__(self, * args):
lm = args[0]
ln = args[1]
values = args[2]
self.matrix = [[0]*ln]*lm
for m in range(lm):
for n in range(ln):
self.matrix[m][n] = values[(m*ln)+n]
vals = [0,1,2,3,4,5]
a = simplematrix(2,3,vals)
When I try to print the matrix, I expect to get [[0,1,2],[3,4,5]], which I get if I run it by hand, on a piece of paper. If I print the matrix from Python I get [[3,4,5],[3,4,5]] instead.
Can anyone tell me why Python acts like this, or if I made some stupid mistake somewhere? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题出在
[[0]*ln]*lm
中。结果由lm
对同一列表的引用组成,因此当您修改一行时,所有行都会发生更改。尝试:
The problem is in
[[0]*ln]*lm
. The result consists oflm
references to the same list, so when you modify one row, all rows appear to change.Try:
Tim 和 aix 的答案纠正了您的错误,但这一步甚至没有必要,您可以使用列表理解在一行中完成整个事情:
您也可以说:
与您已经拥有的相反。这会整理你的代码并使其更加Pythonic。
The answers by Tim and aix correct your mistake, but that step isn't even necessary, you can do the whole thing in one line using a list comprehension:
You can also say:
as opposed to what you already have. This tidies up your code and makes it more Pythonic.
问题是
self.matrix = [[0]*ln]*lm
不会给您一个lm
单独子列表的列表,而是一个列表lm
引用单个相同列表[[0]*ln]
。尝试一下
(如果您使用的是 Python 2,请改用
xrange(lm)
)。The problem is that
self.matrix = [[0]*ln]*lm
doesn't give you a list oflm
separate sublists, but a list oflm
references to the single same list[[0]*ln]
.Try
(If you're on Python 2, use
xrange(lm)
instead).