8

関数をランダムに選択する方法はありますか?

例:

from random import choice

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

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

print(choice(random_function_selector))

上記のコードは、ランダムに選択された関数だけでなく、3 つの関数すべてを実行するようです。これを行う正しい方法は何ですか?

4

5 に答える 5

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

print choice(random_function_selector)()

Python 関数は第一級のオブジェクトです。それらを呼び出さずに名前で参照し、後で呼び出すことができます。

元のコードでは、3 つすべてを呼び出してから、結果の中からランダムに選択していました。ここでは、関数をランダムに選択して呼び出します。

于 2013-01-04T03:12:57.210 に答える
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)

楽しみのために:

関数を実際に定義する前に関数の選択肢のリストを本当に定義したい場合は、追加の間接レイヤーを使用してそれを行うことができることに注意してください (ただし、私はお勧めしません。私は見えます...):

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()
于 2013-01-04T03:13:09.520 に答える
4

ほとんど -- 代わりにこれを試してください:

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

print(choice(random_function_selector)())

random_function_selectorこれにより、それらの関数を呼び出した結果ではなく、関数自体がリストに割り当てられます。次に、 でランダム関数を取得しchoice、それを呼び出します。

于 2013-01-04T03:13:49.207 に答える
0
  1. あなたが持っている要素の数までランダムな整数を生成します
  2. この数に応じて関数を呼び出す

インポートランダム

choice = random.randomint(0,3)
if choice == 0:
  foo()
elif choice == 1:
  foobar()
else:
  fudge()
于 2013-01-04T03:12:13.540 に答える
-1

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()
于 2013-01-04T03:14:39.130 に答える