我一次又一次收到此错误TypeError:无法将序列乘以“ list”类型的非整数

问题描述

步行 如您在函数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,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_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