简体   繁体   English

Python for循环仅将最后一个循环保存在我的二维数组中

[英]Python for loop only saves the last loop in my 2-d array

I am producing one dimensional random walks and I want my for loop to save the maximum distance from the origin that has been reached so far, as time progresses. 我正在生成一维随机游走,并且希望我的for循环保存随着时间的推移距原点的最大距离。 5 random walks are produced. 产生5次随机游走。 This is my code: 这是我的代码:

for j in range(5):
    r = rand(10000)
    t = range(10000)
    x = zeros(10000)
    y = zeros((10000, 5))
    for i in range(10000):
        walk = r[i]
        if walk < 0.5:
            x[i] = x[i-1] - 1
            y[:,j]= maximum.accumulate(abs(x))
        else:
            x[i] = x[i-1] + 1
            y[:,j]= maximum.accumulate(abs(x))
    plot(t,x, label="Walk %d" %(j+1))

title("1-D Random Walk (Position versus Time)")
xlabel("Time")
ylabel("Position")
legend(loc="best")
grid()

The problem is that after the for loop iterates over the set range (5) the output 2-d array only includes the last iteration. 问题是,在for循环遍历设置范围(5)之后,输出2维数组仅包含最后一次迭代。 Somehow, it overwhites the previous ones, so I would only get a 10000x5 array with only the last row filled in. 不知何故,它使前面的那些变白了,所以我只会得到一个10000x5的数组,只填充最后一行。

How can I make this work? 我该如何进行这项工作?

You've, for some reason, chosen to execute 由于某种原因,您已选择执行

y = zeros((10000, 5))

over and over again, each time through the outer loop. 每次遍历外部循环一次又一次。

As an obvious consequence, only the last assignment to y can possibly "take", evidently overriding any previous assignment to the same name. 显然,只有对y的最后一个赋值才可能“取用”,从而明显地覆盖了先前对相同名称的赋值。 What other behavior could you possibly expect from such repeated assignments?! 您可能会从这种重复的作业中期待什么其他行为?

Move this assignment outside the outer loop, and there will be no "overriding" of the name y . 将此分配移到外部循环之外 ,并且名称y不会“覆盖”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM