更改一个列表中的元素会更改多个列表 [英] Changing an element in one list changes multiple lists

查看:68
本文介绍了更改一个列表中的元素会更改多个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,例如mysolution:

>>>mySolution
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> mySolution[0][0] = 1    
>>> mySolution
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]

预期输出:

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

为什么列表中所有第一元素都更改为1? 我只想将第一个列表的第一个元素更改为1.

why is it that all the 1st elements in my list of list's is being changed to 1? I would only like to change the first element of the first list to 1.

推荐答案

重要的是如何创建原始的mysolution列表.看起来,它包含的列表是同一列表的四倍,这就是为什么对其进行一次更改会使它在所有四个位置都更改的原因.

What matters is how you created your original mysolution list. As it seems, it contains four times the same list which is why changing it once will make it change in all four locations.

要像这样初始化独立的零填充列表,您可以执行以下操作:

To initialize independent zero-filled lists like that, you can do the following:

mysolution = [[0] * 4 for i in range(4)]

这篇关于更改一个列表中的元素会更改多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆