【问题标题】:How to create a list of mutable matrices from a cycle in python?如何从python中的循环创建可变矩阵列表?
【发布时间】:2019-08-22 15:34:18
【问题描述】:

我的目标是进行动态模拟。为此,我创建了一个二维矩阵列表。每个矩阵都应该一次更改一个条目(“时间”瞬间是列表的每个步骤,它是可迭代的)。

我使用这种格式是因为我想在 Mathematica 中使用这个矩阵列表(我用 Python 创建的),使用“Manipulate”函数来可视化动态。

n=3 
M=[[0,0,0][0,1,0][0,0,0]]    # initial matrix M (a simple example)
l=[M]
numbersteps=10
for step in range(1,numbersteps+1):    

    for v1 in range(1,n**2+1):   
        for v2 in range(1,n**2+1):


            i=VertexIndex (M,v1)[0]    # i,j, ki, kj are indexes,
            j=VertexIndex (M,v1)[1]    # which I calculate in the function VertexIndex
            ki=VertexIndex (M,v2)[0]   # VertexIndex returns (int1,int2)
            kj=VertexIndex (M,v2)[1]


            if M[i-1][j-1]==1:  
                M[i-1][j-1]=-1
                M[ki-1][kj-1]=1     # changes the entry M(ki, kj)




    l.append(M)     # list of each matrix M, for each step 

我期待得到

l=[M(step1),M(step2),M(step3),...]`

因为 M 正在更改其条目,所以当我运行不同 M 的序列时,我会看到动态。 但我得到的只是一个最终矩阵 M 的列表,“numbersteps”次,即,

l=[M(finalstep),M(finalstep),M(finalstep),...], such that len(l)=numbersteps.

这有意义吗?我的错误在哪里?感谢您的帮助。

【问题讨论】:

    标签: python python-3.x list matrix wolfram-mathematica


    【解决方案1】:

    对象M 在其初始化过程中只创建一次,因此每次将M 附加到ll.append(M) 时,都会为每次迭代附加对同一对象的引用,因此对象发生变异,对该对象的所有引用的值也会发生变化。

    您可以改为附加列表列表的深层副本(首先添加 from copy import deepcopy):

    l.append(deepcopy(M))
    

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 2016-07-29
      • 2016-05-27
      • 2021-06-03
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多