Setting values in matrices - Python

有些话、适合烂在心里 提交于 2021-02-07 19:58:56

问题


I made i matrix 5x3

field = []
fields = []
    for i in range(0,5):
        for j in range(0,3):
            x = 1
            field.append(x)
    fields.append(field)

When i want to change one field

fields[2][2] = 0

i get this:

fields[0][0] = 1
fields[0][1] = 1
fields[0][2] = **0**
fields[1][0] = 1
fields[1][1] = 1
fields[1][2] = **0**
fields[2][0] = 1
fields[2][1] = 1
fields[2][2] = **0**
fields[3][0] = 1
fields[3][1] = 1
fields[3][2] = **0**
fields[4][0] = 1
fields[4][1] = 1
fields[4][2] = **0**

Instead one change i am getting five


回答1:


Its because you have the reference to the same field across all rows.

You want this:

for i in range(0,5):
    field = []
    for j in range(0,3):
        x = 1
        field.append(x)
    fields.append(field)

field should get reset for every row. That's why you should have it inside the first loop. Now your fields[2][2] = 0 would work.

>>> fields
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> fields[2][2] = 0
>>> fields
[[1, 1, 1], [1, 1, 1], [1, 1, 0], [1, 1, 1], [1, 1, 1]]



回答2:


The reason this happens is that each row of your list refers to the same object, the list named field. You can see this by looking at the id of each row. You will find that:

id(fields[0]) == id(fields[1])
id(fields[0]) == id(fields[2])

and so on. Each row is in fact the same object.

You need to create a separate list for each row:

fields = []
for i in range(0,5):
    field = []
    for j in range(0,3):
        x = 1
        field.append(x)
    fields.append(field)

And now you will see that:

id(fields[0]) != id(fields[1])

and so on. And your attempts to modify individual elements will behave as you intend.

But really, if you want to work with matrices, then you should use numpy.



来源:https://stackoverflow.com/questions/15988855/setting-values-in-matrices-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!