简体   繁体   English

使用 python 绘制 2D 步行

[英]Plotting a 2D walk using python

I am trying to create a very basic walking simulation using python.我正在尝试使用 python 创建一个非常基本的步行模拟。 A random number is generated, determining the direction of each step.生成一个随机数,确定每一步的方向。 I am trying to create a list that contains each y and x coordinate for every step.我正在尝试创建一个列表,其中包含每个步骤的每个 y 和 x 坐标。 Something like this: [[0, 0], [1, 0], [0, 0], [0, -1], [-1, -1]].像这样的东西:[[0, 0], [1, 0], [0, 0], [0, -1], [-1, -1]]。 However, I am having trouble appending the results to the list, making plotting impossible.但是,我无法将结果附加到列表中,从而无法进行绘图。

Code:代码:

steps = 200

x_c = 0
y_c = 0

walk = [[x_c,y_c]]


for i in range(steps):
        direction = np.random.randint(1,5)
        
        if direction == 1:
            x_c += 1
        if direction == 2:
            x_c -= 1
        if direction == 3:
            y_c += 1
        if direction == 4:
            y_c -= 1
            
        walk = [[x_c,y_c]]

At the moment, the code above produces no errors, but it only plots one point on the graph (0,0), I think I know what the problem is (the list only contains 0,0) but I am not sure how to fix this.目前,上面的代码没有产生错误,但它只在图表上绘制了一个点(0,0),我想我知道问题出在哪里(列表只包含 0,0)但我不知道如何解决这个问题。 Thanks.谢谢。

It seems like you keep overwriting the items.似乎您一直在覆盖这些项目。

The line in the for loop walk = [[x_c,y_c]] just keeps on resetting walk to the current value of x_c,y_c. for 循环中的行 walk = [[x_c,y_c]] 只是不断将 walk 重置为 x_c,y_c 的当前值。

Instead use walk.append([x_c,y_c])而是使用 walk.append([x_c,y_c])

steps = 200

x_c = 0
y_c = 0

walk = [[x_c,y_c]]


for i in range(steps):
        direction = np.random.randint(1,5)
        
        if direction == 1:
            x_c += 1
        if direction == 2:
            x_c -= 1
        if direction == 3:
            y_c += 1
        if direction == 4:
            y_c -= 1
            
        walk.append([x_c,y_c])

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

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