在Python3中使用random.choice()

当我尝试将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]

错误:

TypeError: 'method' object is not subscriptable

有什么想法吗?

raners 回答:在Python3中使用random.choice()

您需要将元素包装为可迭代的,是的,但是随后您需要使用括号来调用函数;在第二个示例中,您省略了这些括号,这就是第二个错误的原因。

尝试一下:

c = random.choice([vertex1,vertex2,vertex2])

与创建具有所有可能选择的列表相同:

my_options = [vertex1,vertex2]  # a simple list with elements
c = random.choice(my_options)             # this selects one element from the list

random.choice()的文档。

,
  

有人说要尝试将选择的顺序包装在列表中

他们是对的。但是您不应该将括号替换为正方形。

您想要将列表作为参数传递给random.choice()函数。

    0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . . . . . . . .
2 | . . . . . . . . . .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . . . . . . .
6 | . . . . . . . . . .
7 | . . . . . . . . . .
8 | . . . . . . . . . .
9 | . . . . . . . . . .

    0 1 2 3 4 5 6 7 8 9
--+--------------------
0 | . . . . . . . . . .
1 | . . . . . . . . . .
2 | . . . . . . . . . .
3 | . . . . . . . . . .
4 | . . . . . . . . . .
5 | . . . . . . . . . .
6 | . . . . . . . . . .
7 | . . . . . . . . . .
8 | . . . . . . . . . .
9 | . . . . . . . . . .

它将创建一个包含您的顶点的新列表,并将其作为参数传递给random.choice(),等效于此:

c = random.choice([vertex1,vertex2])
本文链接:https://www.f2er.com/3149380.html

大家都在问