从列表ISU运行函数

2024-04-25 08:16:27 发布

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

我想知道如何从一个列表中运行函数,并使用随机模块调用它们,但我似乎无法让它工作,有人能帮忙吗?下面是一个例子。你知道吗

import random
def word1():
       print "Hello"
def word2():
       print "Hello again"

wordFunctList = [word1, word2]

def run():
       printWord = random.randint(1, len(wordFunctList))-1
       wordFunctList[printWord]
       run()
run()

所以我想在一个无限循环中这样做,但是我得到的输出是

Hello
Hello again

那程序就什么都不做了?有人能帮我吗?顺便说一句,我正在使用应用程序pythonista。我也是个编程高手。我最近刚开始研究python。你知道吗

我问这个问题的全部原因是因为我正在制作一个基于文本的世界生成器,我想为生物群落定义函数,然后在世界生成时从列表中随机调用它们。你知道吗


Tags: 模块函数runhello列表def世界random
1条回答
网友
1楼 · 发布于 2024-04-25 08:16:27

我会这样做:

import random

def word1():
    print "Hello"

def word2():
    print "Hello again"

wordFunctList = [word1,  word2]

def run():
    # Infinite loop, instead of recursion
    while True:
        # Choose the function randomly from the list and call it
        random.choice(wordFunctList)()

run()

阅读this answer。它解释了为什么应该避免尾部递归而使用无限循环。你知道吗

random.choice(wordFunctList)()的解释:

wordFunctList是包含函数对象的列表:

>>> print wordFunctList
[<function word1 at 0x7fcb1f453c08>, <function word2 at 0x7fcb1f453c80>]

random.choice(wordFunctList)选择函数并返回:

>>> random.choice(wordFunctList)
<function word2 at 0x7f9ce040dc80>

random.choice(wordFunctList)()调用返回的函数:

>>> print random.choice(wordFunctList)()
Hello again # Outputs during the function call
None        # Returned value

用括号(random.choice(wordFunctList)()())调用函数的返回值,即None,但是None是不可调用的,这就是为什么会出现错误。你知道吗

相关问题 更多 >