Choosing a function randomly
有随机选择函数的方法吗?
例子:
1 2 3 4 5 6 7 8 9 10 11 12 | from random import choice def foo(): ... def foobar(): ... def fudge(): ... random_function_selector = [foo(), foobar(), fudge()] print(choice(random_function_selector)) |
上面的代码似乎执行所有3个函数,而不仅仅是随机选择的函数。正确的方法是什么?
1 2 3 4 | from random import choice random_function_selector = [foo, foobar, fudge] print choice(random_function_selector)() |
Python函数是第一类对象:您可以按名称引用它们而不调用它们,然后在以后调用它们。
在最初的代码中,您调用了这三个函数,然后在结果中随机选择。这里我们随机选择一个函数,然后调用它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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) |
只是为了好玩:
请注意,如果您真的想在实际定义函数之前定义函数选项列表,您可以使用一个额外的间接层来实现这一点(尽管我不建议这样做--据我所见,这样做没有好处…):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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() |
几乎——试试这个:
1 2 3 4 | from random import choice random_function_selector = [foo, foobar, fudge] print(choice(random_function_selector)()) |
这会将函数本身分配到
一个简单的方法:
1 2 3 4 5 6 7 8 9 | # 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() |
随机进口
1 2 3 4 5 6 7 | choice = random.randomint(0,3) if choice == 0: foo() elif choice == 1: foobar() else: fudge() |