Append不停地追加同一项,不追加正确的项,Python

2024-10-02 20:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我导入的内容:

import random
import matplotlib.pyplot as plt
from math import log, e, ceil, floor
import numpy as np
from numpy import arange,array
import pdb
from random import randint

这里我定义了函数矩阵(p,m)

def matrix(p,m):            # A matrix with zeros everywhere, except in every entry in the middle of the row
    v = [0]*m
    v[(m+1)/2 - 1] = 1
    vv = array([v,]*p)
    return vv

ct = np.zeros(5)            # Here, I choose 5 cause I wanted to work with an example, but should be p in general  

这里我定义了MHops,它基本上取矩阵,矩阵和向量ct的维数,并给出了一个新的矩阵mm和一个新的向量ct

def MHops(p,m,mm,ct):

k = 0
while k < p :                 # This 'spans' the rows
    i = 0
    while i < m :             # This 'spans' the columns
        if mm[k][i] == 0 :
            i+=1
        else:
            R = random.random()
            t = -log(1-R,e)              # Calculate time of the hopping
            ct[k] =  ct[k] + t
            r = random.random()
            if  0 <= r < 0.5 :              # particle hops right
                if 0 <= i < m-1:
                    mm[k][i] = 0
                    mm[k][i+1] = 1
                    break
                else: 
                    break           # Because it is at the boundary
            else:                            # particle hops left 
                if 0 < i <=m-1:    
                    mm[k][i] = 0
                    mm[k][i-1] = 1
                    break
                else:              # Because it is at the boundary
                    break
            break
    k+=1    
return (mm,ct)               # Gives me the new matrix showing the new position of the particles and a new vector of times, showing the times taken by each particle to hop

现在我想做的是迭代这个过程,但是我想能够可视化列表中的每一步。简而言之,我要做的是: 1创建表示晶格的矩阵,其中0表示该槽中没有粒子,1表示该槽中有粒子。 2创建一个函数MHops,它模拟一步的随机游走,给我一个新的矩阵和一个向量ct,它显示粒子移动的时间。你知道吗

现在我想要一个向量或数组,其中有2*n个对象,即矩阵mm和向量ct,用于n次迭代。我想在一个数组,列表或类似的东西,因为我需要稍后使用它们。你知道吗

我的问题开始了:

我创建一个空列表,在while循环的每次迭代中使用append来追加项。然而,我得到的结果是一个列表d,其中n个相等的对象来自上一次迭代!

因此,我的迭代函数如下:

def rep_MHops(n,p,m,mm,ct):
    mat = mm
    cct = ct
    d = []
    i = 0
    while i < n :
        y = MHops(p,m,mat,cct)       # Calculate the hop, so y is a tuple y = (mm,ct)
        mat = y[0]                 # I reset mat and cct so that for the next iteration, I go further
        cct = y[1]
        d.append(mat)
        d.append(cct)
        i+=1
    return d


z = rep_MHops(3,5,5,matrix(5,5),ct)      #If you check this, it doesn't work
print z

但是它不起作用,我不明白为什么。我所做的是使用MHops,然后我想把新的矩阵和向量设置为MHops输出中的矩阵和向量,然后再做一次。但是如果你运行这段代码,你会看到v起作用,也就是说,时间向量增加,晶格矩阵改变,但是当我把它加到d上,d基本上是n个相等对象的列表,其中对象是最后一次迭代。你知道吗

我犯了什么错? 此外,如果您对此代码有任何编码建议,他们将非常欢迎,我不确定这是一种有效的方法。你知道吗

为了更好地理解,我想在另一个函数中使用最终向量d,首先我选择一个随机时间T,然后我基本上检查每个奇数项(每个ct),然后检查每个ct的每个条目,看看这些数字是否小于或等于T。如果发生这种情况,然后粒子的运动发生了,否则就没有了。 从这之后,我将尝试用matpotlibt可视化结果与直方图或类似的东西。你知道吗

有人知道如何在matlab中运行这种模拟吗?你觉得这样容易些吗?你知道吗


Tags: ofthe函数import列表矩阵random向量
1条回答
网友
1楼 · 发布于 2024-10-02 20:30:09

You're passing and storing by references not copies, so on the next iteration of your loop MHops alters your previously stored version in d. Use import copy; d.append(copy.deepcopy(mat)) to instead store a copy which won't be altered later.

为什么?你知道吗

Python通过引用传递列表,并且每个循环都存储对d中相同的矩阵对象的引用

我浏览了python文档,唯一能提到的是 "how do i write a function with output parameters (call by reference)"。你知道吗

下面是一个简单的代码示例:

def rep_MHops(mat_init):
    mat = mat_init
    d = []
    for i in range(5):
        mat = MHops(mat)
        d.append(mat)
    return d


def MHops(mat):
    mat[0] += 1
    return mat

mat_init = [10]
z = rep_MHops(mat_init)
print(z)

当运行时:

[[15], [15], [15], [15], [15]]

Python只通过引用传递可变对象(如列表)。整数不是可变对象,下面是上面示例的一个稍加修改的版本,它对单个整数进行操作:

def rep_MHops_simple(mat_init):
    mat = mat_init
    d = []
    for i in range(5):
        mat = MHops_simple(mat)
        d.append(mat)
    return d


def MHops_simple(mat):
    mat += 1
    return mat

z = rep_MHops_simple(mat_init=10)
print(z)

当运行时:

[11, 12, 13, 14, 15]

这是你所期待的行为。你知道吗

这个答案How do I pass a variable by reference?解释得很好。你知道吗

相关问题 更多 >