如何在Python 2中运行随机函数

Mat*_*att 5 python python-2.7

假设我有两个功能:

functionA()functionB()

我不关心哪个函数运行,但我确实想要其中一个随机运行 - 即,如果我运行脚本一百次,两者都应该播放近50次.

如何将其编程到Python 2中?

ozg*_*gur 3

在 Python 中,函数是一等公民,因此您可以将它们放入列表中,然后每次使用以下方法随机选择其中一个random.choice

>>> import random

>>> functions = [functionA, functionB]
>>> for _ in range(100):
...     function = random.choice(functions)
...     function()
Run Code Online (Sandbox Code Playgroud)