首页 > 解决方案 > 我一次又一次地收到这个错误(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() 

标签: pythonpygamesys

解决方案


导致错误的原因是x_directionx_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


推荐阅读