简体   繁体   中英

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. 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. 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]

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:

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:

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"

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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