我正在尝试编写一段代码来为pyplot中的散点图生成随机游动,但一直出错:TypeError:类型为'NoneType'的对象没有len()
from random import choice
class RandomWalk:
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def get_step(self):
step = (choice([x for x in range(20)])) * (choice([1, -1]))
return step
def fill_walk(self):
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
if x_step == 0 and y_step == 0:
continue
self.x_values = self.x_values.append((self.x_values[-1] + x_step))
self.y_values = self.y_values.append((self.y_values[-1] + y_step))
这是情节代码:
rw = RandomWalk(5_000)
rw.fill_walk()
plt.style.use('classic')
fix, ax = plt.subplots(figsize=(15, 9))
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.rainbow, edgecolors='none', s=5)
ax.scatter(0, 0, c='green', edgecolors='none', s=100)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
plt.show()
由于某种原因,未传递self.x_values,因此我得到此行的TypeError:
while len(self.x_values) < self.num_points:
知道为什么不通过吗?
self.x_values = self.x_values.append(...)
问题在上面的行中-append
仅返回None
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句