[尝试将3个可能的顶点分配给变量c的随机顶点时出现错误。
#Establish locations for the 3 vertices
vertex1 = (0,0)
vertex2 = (canv_width,0)
vertex3 = (canv_width//2,canv_height)
c = random.choice(vertex1,vertex2,vertex3)
错误:
TypeError: choice() takes 2 positional arguments but 4 were given
在线有人说要尝试将选择的顺序包装在列表中。所以我尝试了:
c = random.choice[vertex1,vertex2,vertex2]
错误:
TypeError: 'method' object is not subscriptable
有什么想法吗?
有人说要尝试将选择的顺序包装在列表中
他们是对的。但是您不应该将括号替换为正方形。
您想将列表作为参数传递给函数random.choice()。
c = random.choice([vertex1,vertex2,vertex2])
它创建一个包含您的顶点的新列表,并将其作为参数传递给random.choice(),等效于此:
choices = [vertex1, vertex2, vertex3]
c = random.choice(choices)
您需要将元素包装为可迭代的,是的,但是随后您需要使用括号来调用函数;在第二个示例中,您省略了这些括号,这就是第二个错误的原因。
尝试一下:
c = random.choice([vertex1, vertex2, vertex2])
与创建具有所有可能选择的列表相同:
my_options = [vertex1, vertex2, vertex2] # a simple list with elements
c = random.choice(my_options) # this selects one element from the list
random.choice()
的文档。