python - 我一次又一次地收到这个错误(TypeError:不能将序列乘以非“列表”类型的整数)
问题描述
正如你在函数 def 中看到的那样走路 ,我遇到了一个错误
"can't multiply sequence by non-int of type 'list'".
我正在努力解决它,请有人告诉我这是我的任务。
import matplotlib.pyplot as plt
import random
class RandomWalk():
def __init__(self, num_points = 5000):
#Initialize attributes of a walk
self.num_points = num_points
# walk start at (0, 0)
self.x_value = [0]
self.y_value = [0]
def walk(self):
while len(self.x_value) < self.num_points:
# Decide which direction to go and how far to go in that direction.
x_direction = random.choices([1, -1])
x_distance = random.choices([0, 1, 2, 3, 4])
x_step = x_direction * x_distance # here i am getting this error I'm trying to resolve but not able to fix some body help me...
y_direction = random.choices([1, -1])
y_distance = random.choices([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# Reject moves that go nowhere.
if x_step == 0 and y_step == 0:
continue
# Calculate the next x and y values.
next_x = self.x_value[-1] + x_step
next_y = self.y_value[-1] + y_step
self.x_value.append(next_x)
self.y_value.append(next_y)
# Make a random walk, and plot the points.
rw = RandomWalk()
rw.walk()
plt.scatter(rw.x_value, rw.y_value, s = 15)
plt.show()
解决方案
导致错误的原因是x_direction
和x_distance
是列表。您必须使用random.choice
而不是random.choices
(关注s
最后):
x_direction = random.choice([1, -1])
x_distance = random.choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
虽然random.choice
返回列表的 1 个元素,但random.choices
返回k个元素的列表,其中k是可选参数。看random
推荐阅读
- reactjs - 我不知道为什么我会收到“未捕获的类型错误:无法读取 null 的属性 'map'”
- python - 在 python 中,如何使 main args 全局化
- apache-spark - avsc 中的别名值不显示与 avro 文件相同的值
- python - 使用需要更多参数的 _init_ 嵌入自定义 RNN 单元(3 vs 1)
- c# - 使用 .NET Core 2.2 通过 HttpContext 访问 AD 用户
- javascript - 在循环中多次覆盖元素的样式?
- ios - 错误:方法不会覆盖其超类中的任何方法
- owasp - 如何在 OWASP Zap (GUI) 自动攻击中指定 URL 参数
- python - 转换表以平滑一列中的记录
- android-studio - 无法在 Android Studio 中的“FileMapping”中打开库