简体   繁体   English

从随机 Python 模块中获取 output

[英]Getting output from the random Python module

I'm trying to run a script that takes five functions in a list, and picks one at random using the random module.我正在尝试运行一个脚本,该脚本在列表中采用五个函数,并使用random模块随机选择一个。

myList = [quote1(), quote2(), quote3(), quote4(), quote5()]

def random_output(): random.choice(myList)

print(random_output) 

However, upon running, it just prints all of the quotes at the same time, followed by <function random_output at 0x0000019F66EF4430> .但是,在运行时,它只是同时打印所有引号,然后是<function random_output at 0x0000019F66EF4430>

You should put your functions in myList , not the result of their call .你应该把你的函数放在myList中,而不是它们调用的结果 Then call the function after selecting it with random.choice :然后用 random.choice 选择它后调用random.choice

myList = [quote1, quote2, quote3, quote4, quote5]

def random_output():
    # select a random function
    # call it, and return its output
    return random.choice(myList)()

print(random_output())

You don't need a function A that just calls another function B. Just call function B:您不需要只调用另一个 function B 的 function A。只需调用 function B:

import random

myList = [quote1(), quote2(), quote3(), quote4(), quote5()]
random.choice(myList)

If you really want to put it in a function, maybe because you are doing other thing in there, you should always pass in what your function needs, and return what it produces (this is called a 'pure' function):如果你真的想把它放在 function 中,可能是因为你在那里做其他事情,你应该总是传递你的 function 需要什么,并返回它产生的东西(这称为“纯”函数):

def random_output(aList):
    return random.choice(aList)

Then call it like:然后这样称呼它:

random_output(myList)

If you don't want to call the functions quote1 , quote2 etc yet, then you should not put parentheses after them until you do want to call them.如果你还不想调用函数quote1quote2等,那么你不应该在它们后面加上括号,直到你想调用它们。 For example:例如:

funcs = [quote1, quote2, quote3, quote4, quote5]
random_func = random.choice(funcs)
result = random_func(my_input)

You have to put parentheses to invoke your function:您必须加上括号来调用您的 function:

myList = [quote1(), quote2(), quote3(), quote4(), quote5()]

def random_output(): random.choice(myList)

print(random_output()) <--- Here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM