简体   繁体   English

基于python中的随机数调用不同的函数

[英]Call a different function based on a random number in python

I have 11 different functions named func1, func2, etc. all the way up to func11. 我有11个不同的函数,名为func1,func2等,一直到func11。 I have different combinations of values stored in these functions and I need to draw 5 unique random integers in the interval [1,11] to select which 5 functions I will be using. 我在这些函数中存储了不同的值组合,我需要在区间[1,11]中绘制5个唯一的随机整数,以选择我将使用的5个函数。 I have solved this in this way: 我用这种方式解决了这个问题:

possible_values = range(1,12)
selected_values = random.sample(possible_values,5)

Now to the problem: I need to call the selected 5 functions based on the numbers picked out by random.sample which might be something like: [3,6,7,4,9] 现在问题:我需要根据random.sample选择的数字调用所选的5个函数,这可能是这样的:[3,6,7,4,9]

In other word, I need to call: 换句话说,我需要打电话:

func3()
func6()
func7()
func9()

The order of calls does not matter, but I need to make this work for any random numbers generated. 调用顺序无关紧要,但我需要对生成的任何随机数进行此操作。

1. Solution: You could save all eleven functions into a list or dictionary and call it by index, like this: 1.解决方案:您可以将所有11个函数保存到列表或字典中并通过索引调用它,如下所示:

function_dict = {1:func1, 2:func2, 3:func3, 4:func4, 5:func5, 6:func6, 
                 7:func7, 8:func8, 9:func9, 10:func10, 11:func11}

possible_values = range(1,12)
selected_values = random.sample(possible_values,5)

for key in selected_values:
    function_dict[key]()

2. Solution: If you don't need the random number anyway, you could just randomly choose the functions: 2.解决方案:如果您不需要随机数,您可以随机选择功能:

function_list = [func1, func2, func3, func4, func5, func6, 
                 func7, func8, func9, func10, func11]
for func in random.sample(function_list, 5):
    func()

The faster way to do so would be to user "eval" 更快的方法是用户“eval”

possible_values = range(1,12)
selected_values = random.sample(possible_values,5)
for value in selected_values:
    eval("func" + str(value))

Otherwise you could try this: 否则你可以试试这个:

possible_values = range(1,12)
selected_values = random.sample(possible_values,5)
for value in selected_values:
   all_methods = locals().copy()
   method = all_methods.get("func" + str(value)) 
   method()

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

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