Python 3.x 在Python3中使用random.choice()
当我尝试将3个可能顶点中的随机顶点指定给变量c时,我遇到了一个错误Python 3.x 在Python3中使用random.choice(),python-3.x,list,random,seq,Python 3.x,List,Random,Seq,当我尝试将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
#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
有什么想法吗?您需要将元素包装在一个iterable中,是的,但是您需要使用括号调用函数;在第二个示例中,您省略了这些括号,这就是导致第二个错误的原因 试试这个:
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
文档。您需要将元素包装在一个iterable中,是的,但是您需要使用括号调用函数;在第二个示例中,您省略了这些括号,这就是导致第二个错误的原因 试试这个:
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()
它创建一个包含顶点的新列表,并将其作为参数传递给random.choice(),等效于:
choices = [vertex1, vertex2, vertex3]
c = random.choice(choices)
有人说要试着把一系列的选择打包成一个列表
他们是对的。但是你不应该用方括号代替圆括号
您希望将列表作为参数传递给函数random.choice()
它创建一个包含顶点的新列表,并将其作为参数传递给random.choice(),等效于:
choices = [vertex1, vertex2, vertex3]
c = random.choice(choices)