import matplotlib.pyplot as plt
from random import choice
class RandomWalk():
def __init__(self, num_points = 5000):
"""初步化随机漫步的属性"""
self.num_points = num_points
#初始化,传入实参num_points
#所有随机漫步都始于(0,0)
#创建两个列表用于存储坐标,届时只要plot函数
#传入两个列表即可
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""这个方法生成指定数量的随机漫步点"""
#在内部调用自身的属性要用self
while len(self.x_values) < self.num_points:
#while循环里一直向列表里添加新的位置点的坐标
x_dirction = choice([-1,1])
x_distance = choice([0,1,2,3,4])
x_step = x_distance*x_dirction
y_dirction = choice([-1,1])
y_distance = choice([0,1,2,3,4])
y_step = y_distance*y_dirction
if x_step==0 and y_step==0:
continue
next_x = self.x_values[-1] + x_step
next_y = self.y_values[-1] + y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
rw = RandomWalk()
#创建一个方法的实例
rw.fill_walk()
#生成一些列随机漫步点
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
生成![在这里插入图片描述](https://img-blog.csdnimg.cn/6aaf3793e8064b3bb67c3de38a8db8fc.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAc3NyX2FjdHk=,size_20,color_FFFFFF,t_70,g_se,x_16)
03-17
2676
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-08
376
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-06
298
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)