在矩阵中设置值-Python [英] Setting values in matrices - Python

查看:57
本文介绍了在矩阵中设置值-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将矩阵设为5x3

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

当我想更改一个字段时

fields[2][2] = 0

我明白了:

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

推荐答案

这是因为您在所有行中都引用了相同的 field .

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

您想要这个:

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

field 应该为每一行重置.这就是为什么您应该在第一个循环中包含它.现在您的 fields [2] [2] = 0 可以正常工作.

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]]

这篇关于在矩阵中设置值-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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