有没有办法随机选择一个功能?
示例:
from random import choice
def foo():
...
def foobar():
...
def fudge():
...
random_function_selector = [foo(), foobar(), fudge()]
print(choice(random_function_selector))
上面的代码似乎执行所有3个函数,而不仅仅是随机选择的函数。这样做的正确方法是什么?
答案 0 :(得分:14)
from random import choice
random_function_selector = [foo, foobar, fudge]
print choice(random_function_selector)()
Python函数是第一类对象:您可以通过名称引用它们而不调用它们,然后再调用它们。
在原始代码中,您调用了所有三个,然后在结果中随机选择。这里我们随机选择一个函数,然后调用它。
答案 1 :(得分:6)
from random import choice
#Step 1: define some functions
def foo():
pass
def bar():
pass
def baz():
pass
#Step 2: pack your functions into a list.
# **DO NOT CALL THEM HERE**, if you call them here,
#(as you have in your example) you'll be randomly
#selecting from the *return values* of the functions
funcs = [foo,bar,baz]
#Step 3: choose one at random (and call it)
random_func = choice(funcs)
random_func() #<-- call your random function
#Step 4: ... The hypothetical function name should be clear enough ;-)
smile(reason=your_task_is_completed)
只是为了好玩:
请注意,如果您真的要定义之前的功能选项列表实际定义函数,可以使用额外的间接层(尽管我 NOT 强烈>推荐它 - 据我所知,这样做是没有优势的......):
def my_picker():
return choice([foo,bar,baz])
def foo():
pass
def bar():
pass
def baz():
pass
random_function = my_picker()
result_of_random_function = random_function()
答案 2 :(得分:3)
差不多 - 试试这个:
from random import choice
random_function_selector = [foo, foobar, fudge]
print(choice(random_function_selector)())
这会将函数本身分配到random_function_selector
列表中,而不是调用这些函数的结果。然后,您使用choice
获得随机函数,并将其调用。
答案 3 :(得分:-1)
导入随机
choice = random.randomint(0,3)
if choice == 0:
foo()
elif choice == 1:
foobar()
else:
fudge()
答案 4 :(得分:-1)
一种直截了当的方式:
# generate a random int between 0 and your number of functions - 1
x = random.choice(range(num_functions))
if (x < 1):
function1()
elif (x < 2):
function2()
# etc
elif (x < number of functions):
function_num_of_functions()