如何将for循环内for循环的输出添加到列表列表?蟒蛇

时间:2020-07-02 06:03:16

标签: python numpy for-loop montecarlo

我试图将在for循环内的for循环中完成的(蒙特卡洛路径)计算结果输出到列表列表。但是,我只得到一份清单。我在下面指出了我尝试过的几件事。

我得到的结果是: card_number

我期望的是:[path1]每个[[path1], [path2], ..., [path100]]应该是从path开始的steps值的列表。

有什么建议吗?

s0

2 个答案:

答案 0 :(得分:0)

您需要做的是在内循环中生成一个路径,然后将其追加到外循环中的路径列表中,并在函数末尾返回该列表:

import numpy as np

num_reps = 100
s0 = 10
steps = 6

def func(num_reps, s0, steps):
    paths = []
    for j in range(num_reps):
        path = [s0]
        st = s0
        for i in range(int(steps)):
            st = st*np.random.normal(0, 1)
            path.append(st)
        paths.append(path)
    return paths

a = func(num_reps, s0, steps)
print(a)

样本输出:

[
 [10, -16.032722636966014, 3.7409928347961676, 2.627699221438861, 0.028916747229045144, 0.018945060221139155, 0.012497699758698825],
 [10, 10.900456668192026, 10.821821167576429, 11.673219600653663, 8.739058453116968, 11.597769227413888, 5.365291250490312],
 ... 98 more ...
]

答案 1 :(得分:0)

您可以使用'yield'并编写一个生成器

def path_generator(num_reps, s0, steps):
    for j in range(num_reps):
        path = [s0]
        st = s0
        for i in range(int(steps)):
            st = st*np.random.normal(0, 1)
            path.append(st)
        yield path

for path in path_generator(num_reps, s0, steps):
    print path