繁体   English   中英

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

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

我有两个函数执行不同的操作,但我希望它们在另一个 function 中随机调用。

例如。

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

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

将函数收集在一个列表中,并随机选择其中一个(使用random.choice )并调用它!

>>> def f2():
        return 2

>>> def f1():
        return 1

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

这是可能的,因为Python函数是一流的对象。 在Python的一流对象上阅读此链接

另一种方法......而不是选择 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())

output:

Good Night
Hello

暂无
暂无

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

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