Python 函数内的多值参数

问题描述

我有用 Python 生成少数派游戏模型的代码。我正在为具有单个值的参数运行我的代码,例如N = 101,它工作正常,但我希望能够为同一参数的多个值运行它,例如N = 101,201,301。我不能只设置一个列表,因为我的代码有很多 numpy 数组,所以需要匹配我的所有数组等。 我现在已经将我的代码存储到一个函数中:

def mg_theory(N,time,S,M):
    # index to how we pick out a strategy
    index = 1 - 2 * np.random.rand(N,M,S)

    # allocating strategy randomly to all players for past m weeks
    # each strategy is different for all players,each number corresponds to a different strategy
    # some may have same strategy
    outcomes = np.random.rand(N,S)

    # guess randomly how many people are going for first m weeks
    history = np.random.randint(0,N,size=2 * M)
    history = np.reshape(history,(history.shape[0],1))
....
etc 
(rest of code)

如您所见,我有 4 个参数,其中 2 个(N 和 M)我想要多个值。 有人知道吗?

解决方法

如果我理解正确的话,一种选择是使用如 here 所述的列表推导式。

对于您的示例,您可以使用以下命令运行您的函数:

[mg_theory(N,time="something",S="something",M) for N in [1,2,3] for M in [4,5,6]]

这会将您的输出存储为列表。

我知道在你的问题中你说你的数据在 numpy 数组中,要使上面的例子工作,你需要将 2 个硬编码列表更改为你的实际数据(我不知道你的数组结构是什么所以不能将它包含在我的答案中)。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...