简体   繁体   English

Python function 内的多值参数

[英]Python multiple valued parameters within function

I have code which produces a minority game model in Python.我有在 Python 中产生少数游戏 model 的代码。 I am running my code for parameters with single values,eg N = 101 and it works fine, but I want to be able to run this for multiple values for the same parameter,eg N = 101,201,301.我正在为具有单个值的参数运行我的代码,例如 N = 101,它工作正常,但我希望能够为同一参数的多个值运行它,例如 N = 101,201,301。 I can't just set a list since my code has a lot with numpy arrays, so need to match all my arrays etc. I have now stored my code into a function as such: I can't just set a list since my code has a lot with numpy arrays, so need to match all my arrays etc. I have now stored my code into a function as such:

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)

As you can see I have 4 parameters, 2 of which (N and M) I would like to have multiple values.如您所见,我有 4 个参数,其中 2 个(N 和 M)我希望有多个值。 Anyone has a clue?有人有线索吗?

If I understand you correctly, one option would be to use a list comprehension as described here .如果我理解正确,一种选择是使用此处描述的列表理解。

For your example you could run your function using:对于您的示例,您可以使用以下命令运行 function:

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

This would store your outputs as a list.这会将您的输出存储为列表。

I know in your question you said your data are in numpy arrays, to make the above example work you would need to change the 2 hard-coded lists to be your actual data (I don't know what your array structure is so cannot include it in my answer).我知道在您的问题中您说您的数据在 numpy arrays 中,要使上述示例正常工作,您需要将 2 个硬编码列表更改为您的实际数据(我不知道您的数组结构是什么,所以不能包括在我的回答中)。

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

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