Choosing a function randomly

2020-01-27 08:18发布

Is there a way to choose a function randomly?

Example:

from random import choice

def foo():
    ...
def foobar():
    ...
def fudge():
    ...

random_function_selector = [foo(), foobar(), fudge()]

print(choice(random_function_selector))

The code above seems to execute all 3 functions, not just the randomly chosen one. What's the correct way to do this?

标签: python random
5条回答
倾城 Initia
2楼-- · 2020-01-27 08:39
from random import choice
random_function_selector = [foo, foobar, fudge]

print choice(random_function_selector)()

Python functions are first-class objects: you can refer to them by name without calling them, and then invoke them later.

In your original code, you were invoking all three, then choosing randomly among the results. Here we choose a function randomly, then invoke it.

查看更多
时光不老,我们不散
3楼-- · 2020-01-27 08:46

Almost -- try this instead:

from random import choice
random_function_selector = [foo, foobar, fudge]

print(choice(random_function_selector)())

This assigns the functions themselves into the random_function_selector list, rather than the results of calling those functions. You then get a random function with choice, and call it.

查看更多
\"骚年 ilove
4楼-- · 2020-01-27 08:46
  1. Generate a random integer up to how many elements you have
  2. Call a function depending on this number

import random

choice = random.randomint(0,3)
if choice == 0:
  foo()
elif choice == 1:
  foobar()
else:
  fudge()
查看更多
祖国的老花朵
5楼-- · 2020-01-27 08:48

One straightforward way:

# 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()
查看更多
可以哭但决不认输i
6楼-- · 2020-01-27 08:55
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)

Just for fun:

Note that if you really want to define the list of function choices before you actually define the functions, you can do that with an additional layer of indirection (although I do NOT recommend it -- there's no advantage to doing it this way as far as I can see...):

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()
查看更多
登录 后发表回答