有没有办法让python中的turtle运行我创建的随机函数?

fd3cxomn  于 2023-02-18  发布在  Python
关注(0)|答案(1)|浏览(104)

我从random中导入choice并尝试将我定义的函数放入一个列表中,然后输入:

print(choice([SonicTheHedgehogDrawing(), 
              turtle.KnucklesTheEchidnaDrawing(), 
              turtle.MilesTailsProwlerDrawing(), 
              turtle.BeanTheDynamiteDrawing(), 
              turtle.AmyTheHedgehogDrawing(), 
              turtle.EggmanDrawing(),
              turtle.RougeTheBatDrawing(), 
              turtle.BlazeTheCatDrawing()]))

我原以为它会随机选择其中一个函数,但它只是从第一个函数开始,然后一旦它清除屏幕,就会继续列表中的下一个函数,直到它将它们全部运行。

nfs0ujit

nfs0ujit1#

通过写[SonicTheHedgehogDrawing(), turtle.KnucklesTheEchidnaDrawing(), turtle.MilesTailsProwlerDrawing(), turtle.BeanTheDynamiteDrawing(), turtle.AmyTheHedgehogDrawing(), turtle.EggmanDrawing(), turtle.RougeTheBatDrawing(), turtle.BlazeTheCatDrawing()],你创建了一个所有函数调用结果的列表,要在计算之前把函数收集到列表中,省略大括号(),如下所示:[SonicTheHedgehogDrawing, turtle.KnucklesTheEchidnaDrawing, turtle.MilesTailsProwlerDrawing, turtle.BeanTheDynamiteDrawing, turtle.AmyTheHedgehogDrawing, turtle.EggmanDrawing, turtle.RougeTheBatDrawing, turtle.BlazeTheCatDrawing]。但之后必须调用choice的结果一次:

print(choice([...])())
                   ^
                   |
                   |
                  here

相关问题