python遍历列表并在随机点处停止

问题描述 投票:0回答:2

我正在尝试使海龟绕圈移动并随机停在某个点,下面是我所拥有的,但是我不确定如何使其随机停在某个点。我尝试使用random.choice,但这会使乌龟打破圆圈并移动到该点,但是我希望它以连续的圆圈移动并在一个点处停止。坐标是为了画圆

coordinates = ((20,-125),(50,-115),(80,-95),(100,-75),(120,-50),(130,-20),(125,20),(115,45),(100,75),(75,100),(45,115),(20,120),(-15,120),(-45,115),(-70,100),(-95,70),(-115,50),(-125,20),(-125,-15),(-115,-50),(-100,-75),(-75,-100),(-45,-115),(-10,-125))

for i in coordinates:
    pointer.goto(i)

python
2个回答
0
投票

我想这会起作用:

import random
coordinates = ((20,-125),(50,-115),(80,-95),(100,-75),(120,-50),(130,-20),(125,20),(115,45),(100,75),(75,100),(45,115),(20,120),(-15,120),(-45,115),(-70,100),(-95,70),(-115,50),(-125,20),(-125,-15),(-115,-50),(-100,-75),(-75,-100),(-45,-115),(-10,-125))

coordinates = [x for x in coordinates]

random.shuffle(coordinates)
for i in coordinates:
    ## do something

0
投票

我知道您想按顺序执行元组中的每个元素,并在随机点处停止。您可以拥有一个小于列表长度的随机整数,然后在此处停止,如下所示:

import random

coordinates = ((20,-125),(50,-115),(80,-95),(100,-75),(120,-50),(130,-20),(125,20),(115,45),(100,75),(75,100),(45,115),(20,120),(-15,120),(-45,115),(-70,100),(-95,70),(-115,50),(-125,20),(-125,-15),(-115,-50),(-100,-75),(-75,-100),(-45,-115),(-10,-125))

stop_point = random.randrange(len(coordinates))

for i in coordinates[:stop_point]:
    pointer.goto(i)
推荐问答
热门问答
最新问答