如何将函数插入数组而不调用它?

2024-09-28 16:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个pygame代码,它有一些函数,我想能够把函数apple1()和apple2()放在列表中,而不需要立即调用它,然后能够从列表中调用它。你知道吗

这就是我所尝试的:

 #for all the apple
 def apple1():
   pygame.draw.rect(screen,COLOR.GREEN, [ posR,posU, apblock, apblock])

 def apple2():
   pygame.draw.rect(screen,COLOR.RED, [ posiR,posiU, apblock, apblock])

 def random_apple():
   array = [apple1(),apple2()]
   i = random.randrange(0,1)

   x = array[i]
   return x

 def time_apple():
     while time == True:
        random_apple()
        time.sleep(5)

Tags: 函数rectapple列表timedefrandomarray
2条回答

把括号从他们的名字中去掉。你知道吗

另外,我想你要么想用randrange(0,2)要么randint(0,1)。你知道吗

def random_apple():
   array = [apple1,apple2]
   i = random.randrange(0,2)

   x = array[i]
   return x()

编辑: 对于一个更具python功能的解决方案,不需要使用random_apple函数,您可以考虑:

# import as needed
import random
import pygame
import time

#for all the apple
def apple1():
  pygame.draw.rect(screen,COLOR.GREEN, [ posR,posU, apblock, apblock])

def apple2():
  pygame.draw.rect(screen,COLOR.RED, [ posiR,posiU, apblock, apblock])

def time_apple():
  while time == True:
    random.choice([apple1, apple2])()
    time.sleep(5)

请输入这些可调用项的名称:

array = [apple1,apple2]

然后将调用更改为

random_apple()()

相关问题 更多 >