简体   繁体   English

如何在python中随机function内的select函数

[英]How to randomly select functions within a function in python

I have two functions doing different operations but I would like them to be called in another function randomly.我有两个函数执行不同的操作,但我希望它们在另一个 function 中随机调用。

eg.例如。

def func1(): do something
def funct2(): do something else

def func3(): select funct1() or funct2() randomly

Collect the functions in a list and randomly choose one of them (using random.choice ) and call it! 将函数收集在一个列表中,并随机选择其中一个(使用random.choice )并调用它!

>>> def f2():
        return 2

>>> def f1():
        return 1

>>> fns = [f1, f2]
>>> from random import choice
>>> choice(fns)()
1
>>> choice(fns)()
2

This is possible because Python functions are first class objects. 这是可能的,因为Python函数是一流的对象。 Read up this link on first class objects in Python . 在Python的一流对象上阅读此链接

Another way of doing it...Instead of choosing function choose digits and assign functions to them另一种方法......而不是选择 function 选择数字并为其分配功能

import random
def f1():
    print('Good Morning')
    return 'Hi'
def f2():
    print('Good Night')
    return 'Hello'
if random.randint(1,2)==1:
    print(f1())
else:
    print(f2())

The output: output:

Good Night
Hello

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

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