[英]Assigning element of list of lists by index sets all first elements of the lists
I have a list of 3 values per month that a initialized like this: 我每个月都有3个值的列表,像这样初始化:
v=[[0.0,0.0,0.0]]*12
In 2 nested loops I want to add a value to an element: 在2个嵌套循环中,我想为一个元素添加一个值:
v[month-1][pos] += row[0]
At one point in the execution of the code month-1 = 8
and pos = 0
. 在执行代码
month-1 = 8
和pos = 0
某一时刻。 row[0]
which I get from a query to a database is 1.0
. 从查询到数据库的
row[0]
是1.0
。
Strangely as result I get [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0,....
结果很奇怪,我得到了
[[1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0,....
So the first element of every sub-list is set to 1.0
. 因此,每个子列表的第一个元素都设置为
1.0
。 How can this happen? 怎么会这样 Even more strange is if I debug the code and manually set the value
v[8][0]=9
or so it works as intended. 更奇怪的是,如果我调试代码并手动设置值
v[8][0]=9
左右,那么它将按预期工作。
When you do this v=[[0.0,0.0,0.0]]*12
you are getting a list with 12 references to the same list, to fix that use a comprehension instead: 当您执行
v=[[0.0,0.0,0.0]]*12
您将获得一个包含12个对同一列表的引用的列表,以改正使用理解:
v = [[0.0,0.0,0.0] for _ in range(12)]
Usually the *
used like this should not be wanted to use over mutable elements. 通常,不希望在可变元素上使用这样的
*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.